使用C#实现基于TCP和UDP协议的网络通信程序的基本示例

2019-12-30 11:57:35丽君

 

C#中使用UDP通信
UDP通信是无连接通信,客户端在发送数据前无需与服务器端建立连接,即使服务器端不在线也可以发送,但是不能保证服务器端可以收到数据。
服务器端代码:


static void Main(string[] args) 
    { 
      UdpClient client = null; 
      string receiveString = null; 
      byte[] receiveData = null; 
      //实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点 
      IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0); 
 
      while (true) 
      { 
        client = new UdpClient(11000); 
        receiveData = client.Receive(ref remotePoint);//接收数据 
        receiveString = Encoding.Default.GetString(receiveData); 
        Console.WriteLine(receiveString); 
        client.Close();//关闭连接 
      } 
    } 

客户端代码:


static void Main(string[] args) 
    { 
      string sendString = null;//要发送的字符串 
      byte[] sendData = null;//要发送的字节数组 
      UdpClient client = null; 
 
      IPAddress remoteIP = IPAddress.Parse("127.0.0.1"); 
      int remotePort = 11000; 
      IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点 
 
      while (true) 
      { 
        sendString = Console.ReadLine(); 
        sendData = Encoding.Default.GetBytes(sendString); 
 
        client = new UdpClient(); 
        client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点 
        client.Close();//关闭连接 
      } 
    } 

C#,TCP,UDP,网络通信程序



注:相关教程知识阅读请移步到c#教程频道。