C# UDP通讯实例
2021-06-04 05:01
标签:values art eve row code local length 参数 als 1、发送方代码 2、接收方代码 3、UdpService代码 C# UDP通讯实例 标签:values art eve row code local length 参数 als 原文地址:https://www.cnblogs.com/lzsin/p/10868814.htmlvoid SendMsg(string toip, int port )
{
try
{
string message="发送内容";
UdpClient udpclient = new UdpClient();
IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Parse(ip), port);
byte[] data = Encoding.Default.GetBytes(message);
udpclient.Send(data, data.Length, ipendpoint);
udpclient.Close();
}
catch (Exception ex)
{
MessageBox.Show("UDP发送数据" + ex.ToString());
}
}
public UdpService udp;
a>实例化、初始化接收事件
udp = new UdpService(fromip, 60000, "127.0.0.1", 60000);
udp.EvtGetValues+=new UdpService.GetRecevice(udp_EvtGetValues);
b>启动UDP
udp.TurnOn();
c>停止UDP
udp.TurnOff();
d>接收事件处理
void udp_EvtGetValues(byte[] ReceviceBuff)
{
//string message = Encoding.UTF8.GetString(ReceviceBuff, 0, ReceviceBuff.Length);
//可接收中文内容
Encoding ei=Encoding.GetEncoding(936);
string message = ei.GetString(ReceviceBuff, 0, ReceviceBuff.Length);
if (message.Length > 0)
{
// 处理接收逻辑
}
}
public class UdpService
{
#region 内部变量
string devIP = "127.0.0.1";
int devPort = 60000;
UdpClient mySocket;
string meIP = "127.0.0.1";
int mePort = 60000;
IPEndPoint RemotePoint;
bool isRunning = false;
bool isOpen = false;
List