基于UDP的网络通讯(C#)

基于UDP的网络通讯需要用到System.net命名空间里的UdpClient对象。

 

UDPClient 类的使用说明:
(1)Receive方法:
Byte[] Recieve(ref IPEndPoint iep)
以下为示范Receive()方法的使用:

 

//创建一个UdpClient来读输入数据
UdpClient receiveingUdpClient=new UdpClient();
//创建一个IPEndPoint来记录发生者的IP地址和端口
IPEndPoint RemoteIpEndPoint=new IPEndPoint(IPAddress.Any,0);
//阻塞知道收到消息来自远程主机的数据报
Byte[] receiveBytes=receiveingUdpClient.Receive(ref RemoteIpEndPoint);
//将获得数据报数据转为ASCII编码
string ReturnData=Encoding.UTF8.GetString(receiveBytes);
//将消息显示在命令行下
Console.WriteLine("收到消息"+ReturnData.ToString());
//通过Address属性获取消息的来源地址并将其IP地址转为字符串显示在命令行下
Console.WriteLine("The message was sent from"+RemoteIpEndPoint.Address.ToString()+" On the port of"+RemoteIpEndPoint.Port.ToString());

 

以上代码首先初始化一个UdpClient对象作为连接端口使用,接着创建一个IPEndPoint对象来保存发送者的IP地址和端口号,发送者的地址信息由发送者提
供,我们使用创建的UdpClient对象的Receive方法通过传入之前创建的保存发送者地址的IPEndPoint对象来获取远程主机的数据报。最后转为UTF8编码形
式并显示。

(2)Send方法
有三种构造函数,分别为
1.Send(byte[] dgram, int bytes);
2.Send(byte[] dgram, int bytes, IPEndPoint iep);
3.Send(byte[] dgram, int bytes, string str,int port);
这里主要用到第2个构造函数,示例代码如下:

//初始化
UdpClient udpClient=new UdpClient();
//获取远程客户端地址和端口
IPAddress remoteIPAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteIPEndPoint 
= new IPEndPoint(remoteIPAddress, 13000);
//发送字节数组
Byte[] sendbytes=Encoding.UTF8.GetBytes("Hello world!");
//向端口为13000的远程主机发送消息
udpClient.Send(sendbytes,sendbytes.Length,remoteIPEndPoint);

 

以下代码是关于服务端经常使用的接收信息的方法:

private void ReceiveMessage()
        {
            
byte[] receiveBytes = null;
            
//在本机指定端口接收
            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any,8002);
            udpReceive 
= new UdpClient(remoteIpEndPoint);
            
//远程客户端
            IPEndPoint iep = new IPEndPoint(IPAddress.Any,0);

            
//接收从远程主机发送过来的信息
            while (true)
            {
                
try
                {
                    receiveBytes 
= udpReceive.Receive(ref iep);
                }
                
catch
                {
                    MessageBox.Show(
"接收到消息错误");
                    
return;
                }

                
string returnData = Encoding.UTF8.GetString(receiveBytes);
                
string message = "接收到" + iep.ToString() + "的消息";
                
if (returnData=="")
                {
                    MessageBox.Show(
"接收到空信息");
                    
return;
                }
                DialogResult result 
= MessageBox.Show(returnData,message);
            }
        }

 

以下是服务端经常使用于发送信息的函数的实现:

 

private void BtnSend_Click(object sender, EventArgs e)
        {
            
if (TbxMessage.Text=="")
            {
                MessageBox.Show(
"消息不能为空!");
                
return;
            }
            
else
            {
                udpSend 
= new UdpClient();
                
//允许发送和接收广播数据报
                udpSend.EnableBroadcast = true;
                
//必须使用组播地址范围内的地址
                IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.10"), 8001);
                
//将发送的数据转为字节数组
                byte[] bytes = Encoding.UTF8.GetBytes(TbxMessage.Text);
                
//发送组播信息
                try
                {
                    
//将发送内容转为字节数组
                    udpSend.Send(bytes, bytes.Length, iep);
                }
                 
//如果发送失败,则给出错误信息
                catch
                {
                    MessageBox.Show(
"发送失败!");
                    
return;
                }
                
//清空TbxMessage中的内容
                TbxMessage.Clear();
                
//光标还原
                TbxMessage.Focus();
            }
        }

 

 以下是客户端经常使用的用于接收服务端信息的函数实现:

private void ReceiveMessage()
        {
            
byte[] bytes = null;
            udpReceive 
= new UdpClient(8001);
            udpReceive.JoinMulticastGroup(IPAddress.Parse(
"224.100.0.10"), 50);
            IPEndPoint iep 
= new IPEndPoint(IPAddress.Any,0);
            
while (true)
            {
                
try
                {
                    bytes 
= udpReceive.Receive(ref iep);
                }
                
catch
                {
                    MessageBox.Show(
"接收到消息错误!");
                    
return;
                }

                
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                
if (str=="")
                {
                    MessageBox.Show(
"接收到空信息!");
                    
return;
                }
                
string message = "来自" + iep.ToString() + "的消息";

                DialogResult result 
= MessageBox.Show(str, message);
            }
        }

 

以下为客户端用于向服务端发送信息的实现过程:

  private void BtnSend_Click(object sender, EventArgs e)
        {
            
byte[] bytes = null;
            
if (TbxMessage.Text=="")
            {
                MessageBox.Show(
"消息不能为空!");
                
return;
            }

            udpSend 
= new UdpClient();
            IPAddress remoteIPAddress 
= IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteIPEndPoint 
= new IPEndPoint(remoteIPAddress, 8002);

            
try
            {
                bytes 
= Encoding.UTF8.GetBytes(TbxMessage.Text);
            }
            
catch
            {
                MessageBox.Show(
"接收到消息错误!");
                
return;
            }

            udpSend.Send(bytes, bytes.Length, remoteIPEndPoint);
            TbxMessage.Clear();
            TbxMessage.Focus();
        }

 

 

posted on 2010-09-05 22:42  晴天1848  阅读(456)  评论(0)    收藏  举报