unity____udp通讯

阅读更多

服务端:

 public class NetWorking : MonoBehaviour
    {

        // Use this for initialization
        void Start()
        {
            Screen.fullScreen = true;
            Debug.Log("networking start");
            InitNet();
         
        }

        Thread myThread;
        public void InitNet()
        {
    
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//接收端
            sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);//广播发送端
            //255.255.255.255 
            sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast, 1);
            iep1 = new IPEndPoint(IPAddress.Broadcast, 8001);
            iep2 =new IPEndPoint(IPAddress.Any, 8002);

            newsock.Bind(iep2);//接收端必须绑定一下

            myThread = new Thread(new ThreadStart(ReceiveSorkets));
            myThread.IsBackground = true;
            myThread.Start();
        }
        string json = null;
        IPEndPoint iep2;
        public void sendMess(string json)
        {
            
            json = Utils.EventHandleToJson("1", "2", "3", "4");
            json = "1" + "|" + "2" + "|"+"plant" +"|"+ "3";
            Debug.Log("json = " + json);

            byte[] data = Encoding.Default.GetBytes(json);
            byte[] utf8Data = Encoding.Convert(Encoding.Default, Encoding.UTF8, data);

            sock.SendTo(utf8Data, iep1);
           
        }
        IPEndPoint iep1;
        Socket sock;
        Socket newsock;

        private void ReceiveSorkets()
        {
            EndPoint point = (EndPoint)iep2;
            while (true)
            {
                byte[] data = new byte[1024];
                //发送接受信息
                int recv = newsock.ReceiveFrom(data, ref point);
                Debug.Log(Encoding.UTF8.GetString(data, 0, recv));
                string json = Encoding.UTF8.GetString(data, 0, recv);
                if (UdpData != null)
                {
                    UdpData(json);
                }
            }
        }
        public void sendSolvedMessage(string id, string gid, string objectType, string dealingState)
        {
                //string json = null;
                //json = Utils.EventHandleToJson(id, gid, objectType, dealingState);
                //byte[] data = new byte[1024];
                //data = Encoding.Unicode.GetBytes(json);
                //newsock.SendTo(data, data.Length, SocketFlags.None, Remote);

               //son = Utils.EventHandleToJson("1", "2", "3", "4");
                json = gid + "|" + id + "|" + objectType + "|" + dealingState;
                Debug.Log("json = " + json);

                byte[] data = Encoding.UTF8.GetBytes(json);
                byte[] utf8Data = Encoding.Convert(Encoding.Default, Encoding.UTF8, data);

                sock.SendTo(utf8Data, iep1);
            
        }
	
		//关闭Socket
        public void NetClosed()
        {
            // Debuger.LogError("NetClosed");
            if (newsock != null)
            {
                 newsock.Close();
                 newsock = null;
            }
            if (sock != null)
            {
                sock.Close();
                sock = null;
            }
        }

        void OnDestroy()
        {
            NetClosed();
        }
}

 客户端:

public class NetWorking : MonoBehaviour
{


     public NetWorkingMsg netWrokingMsg;

    // Use this for initialization
    void Start()
    {
       
        InitNet();
    }

    
    //本地socket

    Socket APPSocket;
    Socket SendSocket;

    //server目标
    EndPoint ServerRemote;

    string input, stringData;
    IPEndPoint iep;
    public void InitNet()
    {

		ipep = new IPEndPoint(IPAddress.Parse("192.168.0.131"), 8001);

        
        //定义网络类型,数据连接类型和网络协议UDP
        APPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


         iep = new IPEndPoint(IPAddress.Any, 8001);
        APPSocket.Bind(iep);

        SendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
   
        isRun = true;
        myThread = new Thread(new ThreadStart(ReceiveSorket));
        myThread.IsBackground = true;
        myThread.Start();
	
    }

    Thread myThread;
    int recv;
    IPEndPoint remote;
    Pack pack = new Pack();

  
    Int32 timeStamp;

	private bool isRun = false;
    //接收数据

    //供UDP使用 start
    public IPAddress broadcast;
    public IPEndPoint ep;
    public UdpClient ReceiveUdpClient;
    private void ReceiveSorket()
    {

        EndPoint ep = (EndPoint)iep; 
		while (isRun)
		{

            byte[] data = new byte[1024];
            int recv = APPSocket.ReceiveFrom(data, ref ep);
  
            stringData = Encoding.UTF8.GetString(data);

            netWrokingMsg.receiveUdp(stringData);	
		}
            
    }


    // 发送消息
    public void SendUdp(string str)
    {
        IPEndPoint sender = new IPEndPoint( IPAddress.Parse(Constant.servicesIP), 8002);
        EndPoint Remote = (EndPoint)sender;
        Debug.Log("zdp senUDP  11111");
        SendSocket.SendTo(Encoding.UTF8.GetBytes(str), Remote);


    }
    public void SendUdpBroadcast()
    { 
            IPEndPoint sender = new IPEndPoint(IPAddress.Broadcast, 8001);
            EndPoint Remote = (EndPoint)sender;
            APPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);//设置该scoket实例的发送形式
        string request = "你好,TEST SEND!";//初始化需要发送而的发送数据
        byte[] buffer = Encoding.Unicode.GetBytes(request);
        APPSocket.SendTo(buffer, Remote);

    }
    //关闭Socket
    public void NetClosed()
    {
        // Debuger.LogError("NetClosed");
        if (APPSocket != null)
        {
            APPSocket.Close();
			APPSocket = null;
        }
        
		if(SendSocket != null)
		{
			
			SendSocket.Close();
			SendSocket = null;
		}
   
		isRun = false;

    }


    void OnDestroy()
    {
        NetClosed();
    }
}

 

你可能感兴趣的:(unity____udp通讯)