using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace _006_UDP进程通信
{
public partial class Form1 : Form
{
//--显示消息回调
private delegate void ShowMessageCallBack(string text);
private ShowMessageCallBack showMessageCallBack;
//--匿名UDP客户端
private UdpClient AnonyUdpClient;
//--实名UDP客户端
private UdpClient myUdpClient;
public Form1()
{
InitializeComponent();
}
//---发送消息按钮被单击事件
private void btn_sendMessage_Click(object sender, EventArgs e)
{
//--判断是否为匿名发送
if (checkbox_hideName.Checked)
{
//--匿名发送
AnonyUdpClient = new UdpClient();
}
//--创建并启动消息线程
Thread sendMessageThread = new Thread(SendMessage);
//--主线程退出,它也退出
sendMessageThread.IsBackground = true;
sendMessageThread.Start();
}
//---发送消息线程
private void SendMessage()
{
//--创建一个IP终端借点
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(textbox_localIP.Text),Convert.ToInt32(textbox_localPort.Text));
//--判断是否为匿名发送
//--准发送数据
byte[] sendData = Encoding.Default.GetBytes(textbox_sendMessage.Text);
if (checkbox_hideName.Checked)
{
//--匿名发送
AnonyUdpClient.Send(sendData, sendData.Length, ipEndPoint);
//--关闭
AnonyUdpClient.Close();
}
else
{
//--实名发送
myUdpClient.Send(sendData, sendData.Length, ipEndPoint);
}
}
//--消息接受线程
private void ReceiveMessage()
{
//--实例化一个IP终结点
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
while(true)
{
try
{
//--获取消息
byte[] getData = myUdpClient.Receive(ref ipEndPoint);
string msg = Encoding.Default.GetString(getData);
listbox_showMessage.Invoke(showMessageCallBack, ipEndPoint.ToString() + ":" + msg);
}
catch(ThreadAbortException)
{
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void btn_start_Click(object sender, EventArgs e)
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(textbox_localIP.Text), Convert.ToInt32(textbox_localPort.Text));
//--实例化UDP客户端
myUdpClient = new UdpClient(ipEndPoint);
//---创建并启动消息接收线程
Thread ReceiveMessageThread = new Thread(ReceiveMessage);
ReceiveMessageThread.IsBackground = true;
ReceiveMessageThread.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
//--初始化回调
showMessageCallBack = new ShowMessageCallBack(ShowMessage);
}
//--显示消息被委托的方法
private void ShowMessage(string text)
{
listbox_showMessage.Items.Add(text);
}
}
}
代码篇C#网络编程之UDP进程通信
最新推荐文章于 2020-08-03 08:46:46 发布