天天看點

簡易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