c#实现udp通信
一、udp服务器
- 1、关键类: udpclient、ipendpoint;
- 2、实例化一个udpclient对象;
- 3、使用ipendpoint建立与远程对象的连接;
- 4、开一个异步新任务发送数据;
- 5、主进程接收数据;
示例代码:
public static void main()
{
udpclient client = new udpclient(8889);
cancellationtokensource cts = new cancellationtokensource();
ipendpoint remotepoint = new ipendpoint(ipaddress.any, 0);
task.factory.startnew(() =>
{
while (!cts.iscancellationrequested)
{
string? sendmessage = console.readline();
if (sendmessage != null)
{
byte[] data = encoding.default.getbytes(sendmessage);
client.send(data, remotepoint);
}
}
}, cts.token);
while (true)
{
byte[] recvdata = client.receive(ref remotepoint);
if (recvdata != null)
{
string recvmessage = encoding.utf8.getstring(recvdata);
if (recvmessage == "quit")
{
cts.cancel();
client.close();
return;
}
stringbuilder sb = new stringbuilder("客户端:");
sb.append(recvmessage);
console.writeline(sb);
}
}
}二、udp客户端
- 1、关键类: udpclient、ipendpoint;
- 2、实例化一个udpclient对象;
- 3、使用ipendpoint建立与远程服务器的连接;
- 4、开新任务接收数据;
- 5、主进程发送数据;
示例代码:
public static void main()
{
udpclient client = new udpclient(8888);
ipaddress remoteip = ipaddress.parse("127.0.0.1");
int remoteport = 8889;
ipendpoint? remoteendpoint = new ipendpoint(remoteip, remoteport);
cancellationtokensource cts = new cancellationtokensource();
task.factory.startnew(() =>
{
while (!cts.iscancellationrequested)
{
try
{
byte[] data = client.receive(ref remoteendpoint);
if (data != null)
{
stringbuilder sb = new stringbuilder("服务器:");
sb.append(encoding.utf8.getstring(data));
console.writeline(sb);
}
}
catch (exception ex)
{
console.writeline(ex.tostring());
break ;
}
}
}, cts.token);
while (true)
{
string? sendmessage = console.readline();
if (sendmessage != null)
{
byte[] data = encoding.default.getbytes(sendmessage);
client.send(data, remoteendpoint);
if (sendmessage == "quit")
{
cts.cancel();
client.close();
return;
}
}
}
}三、最终效果

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论