游戏蛮牛学习群(纯技术交流,不闲聊):159852603
游戏蛮牛 手机端
开启辅助访问
 找回密码
 注册帐号

扫一扫,访问微社区

首页   >   博客   >   碎碎

UDPSocket通信 热度 1

个人分类: UDPSocket | 2018-5-25 10:09
标签:UDP socket
0 个评论 | 阅读 242 | 收藏 | 举报
1.客户端代码:

[code]csharpcode:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System;
using UnityEngine.UI;
/// <summary>
/// UDP客户端
/// </summary>
public class clientUDP : MonoBehaviour {
    public Text[] texT;
    public InputField input;
    string receStr;
    //创建连接到服务器对象
    Socket socket;
    //创建连接到服务器的IP地址
    IPAddress ip;
    //IPEndPoint :表示主机地址和端口信息
    IPEndPoint ipEnd;
    //发送数据
    EndPoint endPoint;
    //线程
    Thread connectThread;
    void OnEnable()
    {
        ip = IPAddress.Parse("192.168.2.140");
        ipEnd = new IPEndPoint(ip, 8888);
    }
    // Use this for initialization
    void Start() {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //客户端打开一个端口,设置IP
        socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.140"), 1001));
        endPoint = (EndPoint)ipEnd;
        //开启一个线程连接
        connectThread = new Thread(new ThreadStart(clientReceive));
        connectThread.Start();
    }
    //发送消息
    //要发送的字符串
    string sendStr;
    public void clientSend()
    {
        if (socket != null)
        {
            try
            {
                //把string类型转换为字节
                byte[] b = new byte[1024];
                b = Encoding.UTF8.GetBytes(sendStr);
                // 发送给指定服务端
                socket.SendTo(b, endPoint);
                texT[0].text = "fasongchenggong";
            }
            catch (Exception e)
            {
            }
        }
    }
    //服务器接收
    void clientReceive()
    { 
        while (true)
        {  
            try
            {
                byte[]  receData = new byte[1024];
             int receLen = socket.ReceiveFrom(receData, ref endPoint);//接收数据报 
                receStr = Encoding.UTF8.GetString(receData, 0, receLen);
               // print("客户端接收到消息:"+receStr);
                if (texT[1].text != null)
                {
                    texT[1].text = null;
                    texT[1].text = receStr;
                }
                else
                { texT[1].text = receStr; }
            }
            catch(Exception e)
            {         
                break;
            }
        }
    }
	// Update is called once per frame
	void Update () {
        sendStr = input.GetComponent<InputField>().text;
    }
    //连接关闭
    void OnDisable()
    {
        Quit();
    }
    //连接关闭
    void Quit()
    {
        //关闭线程
        if (connectThread!=null)
        {
            connectThread.Abort();
            connectThread = null;
        }
         //关闭socket
          if(socket !=null)
        {
            socket.Close();
            socket = null;
        }
    }
    //获取本地IP
    public static string GetLocalIP()
    {
        try
        {
            string HostName = Dns.GetHostName();
            IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
            for (int i = 0; i < IpEntry.AddressList.Length; i++)
            {
                if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                {
                    return IpEntry.AddressList[i].ToString();
                }
            }
            return "";
        }
        catch
        {
            return "";
        }
    }
}

2.服务端代码:

[code]csharpcode:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

public class severUDP : MonoBehaviour {
    public InputField input;
    string receStr;
    public Text[] texT;
    //创建服务器连接对象
    Socket sever;
    //设置客户要连接的IP和端口
    IPAddress ip;
    EndPoint endPoint;
    //线程
    Thread thread;
    IPEndPoint ipEndPoint;
    // Use this for initialization
    void OnEnable()
    {
        ip =IPAddress.Parse("192.168.2.140");
    }
    void Start () {
         ipEndPoint = new IPEndPoint(ip, 1001);
		sever = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //服务器打开一个端口,设置IP
        sever.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.140"), 8888));
        //  endPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
        endPoint = (EndPoint)ipEndPoint;
        //开启一个线程连接
        thread = new Thread(new ThreadStart(severReceive));
        thread.Start();
    }
    string sendStr;
 public  void severSend()
    {
        if (sever != null)
        {
            try
            {
                //把string类型转换为字节
                byte[] b = new byte[1024];
                b = Encoding.UTF8.GetBytes(sendStr);
                // 发送给指定服务端
                sever.SendTo(b,endPoint);
                texT[0].text = "发送成功";
            }
            catch (Exception e)
            {           
            }
        }
    }
	void severReceive()
    {
        while(true)
        {
            //用来保存发送方的IP和端号
         //   EndPoint point = new IPEndPoint(IPAddress.Any, 0);
            try
            {           
                byte[] b = new byte[1024];
                int receLen = sever.ReceiveFrom(b, ref endPoint);//接收数据报
                receStr = Encoding.UTF8.GetString(b, 0, receLen); 

                print("接收到消息:"+receStr);
                if (texT[1].text != null)
                {
                    texT[1].text = null;
                    texT[1].text = receStr;
                }
                else
                { texT[1].text = receStr; }
            }
            catch(Exception e)
            {             
                break;
            }
        }
    }
     void OnDisable()
    {
       Quit();
    }
    //连接关闭
     void Quit()
    {
        //关闭线程  
        if (thread != null)
        {
            thread.Abort();
            thread = null;
        }
        //最后关闭socket  
        if (sever != null)
            sever.Close();
        sever = null;
    }

    // Update is called once per frame
    void Update () {
        sendStr = input.GetComponent<InputField>().text;
    }
}

3.场景设置:

4.运行效果:

5.资源包:
链接:https://pan.baidu.com/s/17N0F-uinowM6frIIpXcS1Q 密码:ttwl

1 0

作者的其他最新博客

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册帐号

个人分类

标签

阅读排行

评论排行

推荐博客

最新博客

关闭

站长推荐 上一条 /1 下一条

返回顶部