当前位置: 移动技术网 > IT编程>开发语言>c# > C#中使用UDP通信实例

C#中使用UDP通信实例

2019年07月18日  | 移动技术网IT编程  | 我要评论

网络通信协议中的udp通信是无连接通信,客户端在发送数据前无需与服务器端建立连接,即使服务器端不在线也可以发送,但是不能保证服务器端可以收到数据。本文实例即为基于c#实现的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();//关闭连接 
  } 
}

程序最终运行效果如下:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网