udp通讯

服务器

 void Start()
        {
            InitNet();
        }

        Thread myThread;
        public void InitNet()
        {
            IAsyncResult result = null;

            result = InitUdpNet();

            if (result == null)
                return;
            bool success = result.AsyncWaitHandle.WaitOne(5000, true);
            if (!success)
            {
                //超时
                NetClosed();
                Debug.Log("connect Time Out    Net will reconnect");
                InitNet();
            }
            else
            {
                //与socket建立连接成功,开启线程接受服务端数据。
                // worldpackage = new List<JFPackage.WorldPackage>();
                myThread = new Thread(new ThreadStart(ReceiveSorket));
                myThread.IsBackground = true;
                myThread.Start();
            }
        }
        private void ReceiveSorket()
        {
            while (true)
            {
                byte[] data = new byte[1024];
                //发送接受信息
                recv = newsock.ReceiveFrom(data, ref Remote);
                Debug.Log(Encoding.Unicode.GetString(data, 0, recv));
                newsock.SendTo(data, recv, SocketFlags.None, Remote);
            }
        }

        private IAsyncResult InitUdpNet()
        {
            //得到客户机IP
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, port);
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //绑定网络地址
            newsock.Bind(sender);
                    
            Remote = (EndPoint)(sender);
          
            IAsyncResult result = newsock.BeginConnect(Remote, new AsyncCallback(connectCallback), newsock);
            return result;
        }

        private void connectCallback(IAsyncResult asyncConnect)
        {
            Debug.LogError("connectSuccess");

        }
        int recv;
        Socket newsock;
        EndPoint Remote;
        int port = 8001;

        string stringData;
        // 发送消息
        public void SendUdpBroadcasts()
        {
            //Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint sender = new IPEndPoint(IPAddress.Broadcast, port);
            EndPoint Remote = (EndPoint)sender;
            newsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);//设置该scoket实例的发送形式
            string request = "你好,TEST SEND!";//初始化需要发送而的发送数据
            byte[] buffer = Encoding.Unicode.GetBytes(request);
            newsock.SendTo(buffer, Remote);
        }

        public void SendUdp(string str)
        {
            byte[] data = new byte[1024];
            data = Encoding.Unicode.GetBytes(str);
            newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
        }
	
		//关闭Socket
        public void NetClosed()
        {
            // Debuger.LogError("NetClosed");
            if (newsock != null)
            {
                if (newsock.Connected)
                {
                    newsock.Shutdown(SocketShutdown.Both);
                    newsock.Close();
                }
            }
            newsock = null;

        }


        void OnDestroy()
        {
            NetClosed();
        }

 客户端:

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

    // Update is called once per frame
    void Update()
    {

    }

    Socket server;
    EndPoint Remote;
    string input, stringData;

    public void InitNet()
    {
        //获取本机可用IP地址
        byte[] data = new byte[1024];
       


        Debug.Log("This is a Client, host name is {0}"+ Dns.GetHostName());

        //设置服务IP,设置TCP端口号
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.0.131"), 8001);

        //定义网络类型,数据连接类型和网络协议UDP
        server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        server.Bind(ipep);
        string welcome = "Hello! ";
        data = Encoding.ASCII.GetBytes(welcome);
        server.SendTo(data, data.Length, SocketFlags.None, ipep);
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        Remote = (EndPoint)sender;

        data = new byte[1024];
        //对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制
        //server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);
        recv = server.ReceiveFrom(data, ref Remote);
        Debug.Log("Message received from {0}: "+ Remote.ToString());
        Debug.Log(Encoding.ASCII.GetString(data, 0, recv));
        myThread = new Thread(new ThreadStart(ReceiveSorket));
        myThread.IsBackground = true;
        myThread.Start();
    }

    Thread myThread;
    int recv;
    IPEndPoint remote;
    //接收数据
    private void ReceiveSorket()
    {
        while (true)
        {
           // server.SendTo(Encoding.ASCII.GetBytes("你是谁"), Remote);
            byte[] data = new byte[1024];
            recv = server.ReceiveFrom(data, ref Remote);
            stringData = Encoding.Unicode.GetString(data);
            Debug.Log(stringData);
        }
            
    }


    // 发送消息
    public void SendUdp()
    {

        server.SendTo(Encoding.Unicode.GetBytes("你是谁"), Remote);

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


    }


    void OnDestroy()
    {
        NetClosed();
    }

 

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