技术交流 > 心得分享 > C#网络编程(TCP和UDP)

C#网络编程(TCP和UDP)

TCP需要进行互相连接后才可以进行传输数据;

UDP仅仅是知道IP和端口就可以进行传输数据;


Socket(套接字)编程(Tcp)

使用Tcp协议通讯需要具备以下几个条件:

(1).建立一个套接字(Socket)
(2).绑定服务器端IP地址及端口号--服务器端
(3).利用Listen()方法开启监听--服务器端
(4).利用Accept()方法尝试与客户端建立一个连接--服务器端
(5).利用Connect()方法与服务器建立连接--客户端
(6).利用Send()方法向建立连接的主机发送消息
(7).利用Recive()方法接受来自建立连接的主机的消息(可靠连接)


Socket(套接字)编程(Udp)

基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过 应用层的控制来满足。(不可靠连接)

使用Udp协议通讯需要具备以下几个条件:
(1).建立一个套接字(Socket)
(2).绑定服务器端IP地址及端口号--服务器端
(3).通过SendTo()方法向指定主机发送消息 (需提供主机IP地址及端口)
(4).通过ReciveFrom()方法接收指定主机发送的消息 (需提供主机IP地址及端口)


1.TcpSever

public static void TcpServer(IPEndPoint serverIP)
        {
            Console.WriteLine("客户端Tcp连接模式");
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            tcpServer.Bind(serverIP);
            tcpServer.Listen(100);
            Console.WriteLine("开启监听...");
            new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        TcpRecive(tcpServer.Accept());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                    }
                }
            }).Start();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            tcpServer.Close();
        }

        public static void TcpRecive(Socket tcpClient)
        {
            new Thread(() =>
            {
                while (true)
                {
                    byte[] data = new byte[1024];
                    try
                    {
                        int length = tcpClient.Receive(data);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                    }
                    Console.WriteLine(string.Format("收到消息:{0}",
                    Encoding.UTF8.GetString(data)));
                    string sendMsg = "收到消息!";
                    tcpClient.Send(Encoding.UTF8.GetBytes(sendMsg));
                }
            }).Start();

        }


2.TcpClient

public static void Tcpcolient(IPEndPoint serverIP)
        {
            Console.WriteLine("客户端Tcp连接模式");
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                tcpClient.Connect(serverIP);
            }
            catch (SocketException e)
            {
                Console.WriteLine(string.Format("连接出错:{0}", e.Message));
                Console.WriteLine("点击任何键退出!");
                Console.ReadKey();
                return;
            }
            Console.WriteLine("客户端:client-->server");
            string message = "我上线了...";
            tcpClient.Send(Encoding.UTF8.GetBytes(message));
            Console.WriteLine(string.Format("发送消息:{0}", message));
            new Thread(() =>
            {
                while (true)
                {
                    byte[] data = new byte[1024];
                    try
                    {
                        int length = tcpClient.Receive(data);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                    }
                    Console.WriteLine(string.Format("{0} 收到消息:{1}",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                }
            }).Start();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            tcpClient.Close();
        }


3.UdpServer

public static void UdpServer(IPEndPoint serverIP)
        {
            Console.WriteLine("客户端Udp模式");
            Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(serverIP);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)ipep;
            new Thread(() =>
            {
                while (true)
                {
                    byte[] data = new byte[1024];
                    try
                    {
                        int length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                    }
                    Console.WriteLine(string.Format("{0} 收到消息:{1}",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                    string sendMsg = "收到消息!";
                    udpServer.SendTo(Encoding.UTF8.GetBytes(sendMsg), SocketFlags.None,
                    Remote);
                }
            }).Start();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            udpServer.Close();
        }


4.UdpClient

public static void UdpClient(IPEndPoint serverIP)
        {
            Console.WriteLine("客户端Udp模式");
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            string message = "我上线了...";
            udpClient.SendTo(Encoding.UTF8.GetBytes(message), SocketFlags.None, serverIP);
            Console.WriteLine(string.Format("发送消息:{0}", message));
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;
            new Thread(() =>
            {
                while (true)
                {
                    byte[] data = new byte[1024];
                    try
                    {
                        int length = udpClient.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                    }
                    Console.WriteLine(string.Format("{0} 收到消息:{1}",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                }
            }).Start();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            udpClient.Close();
        }


5.小结

在C#中做UDP和TCP通讯对于开发者来说区别不大,因为.NET已经有完善并且成熟的公共类和方法供我们来进行相关的通讯工作,只要我们稍加学习就可以在C#中运用这两种通讯方式了;

2023-01-18 12:29:08
评论
  • 评论加载中...

评论内容: