UDP通讯,介绍基础 private void btnReceive_Click(object sender, EventArgs e)
{
// 创建接收套接字
IPAddress localIp = IPAddress.Parse(tbxlocalip.Text);
IPEndPoint localIpEndPoint = new IPEndPoint(localIp, int.Parse(tbxlocalPort.Text));
receiveUpdClient = new UdpClient(localIpEndPoint);
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start();
}
//接收消息方法
private void ReceiveMessage()
{
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{ // 关闭receiveUdpClient时此时会产生异常
byte[] receiveBytes = receiveUpdClient.Receive(ref remoteIpEndPoint);
string message = Encoding.Unicode.GetString(receiveBytes);
// 显示消息内容
ShowMessageforView(lstbxMessageView, string.Format("{0}[{1}]", remoteIpEndPoint, message));
}
catch
{
break;
}
}
}
// 利用委托回调机制实现界面上消息内容显示
delegate void ShowMessageforViewCallBack(ListBox listbox, string text);
private void ShowMessageforView(ListBox listbox, string text)
{
if (listbox.InvokeRequired)
{
ShowMessageforViewCallBack showMessageforViewCallback = ShowMessageforView;
listbox.Invoke(showMessageforViewCallback, new object[] { listbox, text });
}
else
{
lstbxMessageView.Items.Add(text);
lstbxMessageView.SelectedIndex = lstbxMessageView.Items.Count - 1;
lstbxMessageView.ClearSelected();
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if (tbxMessageSend.Text == string.Empty)
{
MessageBox.Show("发送内容不能为空", "提示");
return;
}
// 选择发送模式
if (chkbxAnonymous.Checked == true)
{
// 匿名模式(套接字绑定的端口由系统随机分配)
sendUdpClient = new UdpClient(0);
}
else
{
// 实名模式(套接字绑定到本地指定的端口)
IPAddress localIp = IPAddress.Parse(tbxlocalip.Text);
IPEndPoint localIpEndPoint = new IPEndPoint(localIp, int.Parse(tbxlocalPort.Text));
sendUdpClient = new UdpClient(localIpEndPoint);
}
Thread sendThread = new Thread(SendMessage);
sendThread.Start(tbxMessageSend.Text);
}
//发送消息方法
private void SendMessage(object obj)
{
string message = (string)obj;
byte[] sendbytes = Encoding.Unicode.GetBytes(message);
IPAddress remoteIp = IPAddress.Parse(tbxSendtoIp.Text);
IPEndPoint remoteIpEndPoint = new IPEndPoint(remoteIp, int.Parse(tbxSendtoport.Text));
sendUdpClient.Send(sendbytes, sendbytes.Length, remoteIpEndPoint);
sendUdpClient.Close();
// 清空发送消息框
ResetMessageText(tbxMessageSend);
}
// 采用了回调机制
评论