C# udp协议的同步通讯

版权声明:本文为博主原创文章,转载请注明源地址 https://blog.csdn.net/qq_15505341/article/details/79198169

服务器

初始化完,使用GetApp()方法会让主线程停止并等待客户端消息传入,并返回收到的ip和文本

        class UdpSever
        {
            IPEndPoint ip;
            Socket socket;

            public struct App
            {
                public EndPoint endPoint; //客户端的ip
                public string text;
            }
            public UdpSever()
            {
                ip = new IPEndPoint(IPAddress.Any, 2333);//设置ip和端口
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                socket.Bind(ip);
            }

            public App GetApp()
            {
                byte[] data = new byte[1024];
                App app = new App();
                app.endPoint = new IPEndPoint(IPAddress.Any, 0);
                int recv = socket.ReceiveFrom(data, ref app.endPoint);
                app.text = Encoding.Default.GetString(data, 0, recv);
                return app;
            }

            public void Send(App app, string text)
            {
                byte[] data = Encoding.Default.GetBytes(text);
                socket.SendTo(data, data.Length, SocketFlags.None, app.endPoint);
            }
        }

客户端

初始化完后,使用Sent()方法向服务器发送信息并等待服务器返回信息

    class UdpApp
    {
        IPEndPoint ip;
        Socket socket;

        public UdpApp()
        {
            ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2333);//设置ip和端口
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        }

        public string Sent(string text)
        {
            byte[] data = new byte[1024];
            data = Encoding.Default.GetBytes(text);
            socket.SendTo(data, data.Length, SocketFlags.None, ip);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = sender;

            data = new byte[1024];
            int recv = socket.ReceiveFrom(data, ref Remote);
            return Encoding.Default.GetString(data, 0, recv);
        }

    }

抛砖引玉!
参考资料:博客园-sunev-基于C#的UDP协议的同步实现

猜你喜欢

转载自blog.csdn.net/qq_15505341/article/details/79198169