简易TCP+UDP通信

Server:

class Server
    {
        static int port = 17333;
        static void Main(string [] args) {
            //CreatTCPServer();
            CreatUDPClient();
            Console.ReadKey();
        }


        static void CreatTCPServer() {
            TcpListener listener = new TcpListener(System.Net.IPAddress.Any , port);
            listener.Start();
            Console.WriteLine("等待连接...");
            while (true) {
                TcpClient client = listener.AcceptTcpClient();
                NetworkStream ns = client.GetStream();
                byte [] bs = Encoding.ASCII.GetBytes("www.baidu.com");
                ns.Write(bs , 0 , bs.Length);
                ns.Close();
            }
        }

        static void CreatUDPClient() {
            UdpClient listener = new UdpClient(port);
            IPEndPoint remote = new IPEndPoint(IPAddress.Any , port);
            try {
                while (true) {
                    byte [] data = listener.Receive(ref remote);
                    Console.WriteLine("remote:" + remote);
                    Console.WriteLine("msg:" + Encoding.ASCII.GetString(data , 0 , data.Length));
                }
            }
            catch (SocketException e) {
                Console.WriteLine(e.ToString());
            }
            finally {
                listener.Close();
            }
        }
    }

Client:

    class Client
    {
        static int port = 17333;
        static void Main(string [] args) {
            //CreatTCPClient();
            CreatUDPClient();
            Console.ReadKey();
        }

        static void CreatUDPClient() {
            UdpClient client = new UdpClient();
            IPEndPoint remote = new IPEndPoint(IPAddress.Parse("88.22.23.203") , port);
            byte [] b = Encoding.ASCII.GetBytes("www.baidu.com");
            client.Send(b , b.Length , remote);
            Console.WriteLine("send msg to server.");
        }

        static void CreatTCPClient() {
            TcpClient client = new TcpClient("88.22.23.203" , port);
            NetworkStream ns = client.GetStream();
            byte [] b = new byte [1024];
            int len = ns.Read(b , 0 , b.Length);
            string str = Encoding.ASCII.GetString(b , 0 , len);
            Console.WriteLine("Str:" + str);
        }
    }

推荐使用下面的UDP框架(服务器+客户端),集成了KCP,确保数据不丢包,扩展也方便,里面有一套心跳机制以及重连机制。
Unity+UDP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值