gpt4 book ai didi

c# - 多个客户端的C#.NET UDP套接字异步

转载 作者:行者123 更新时间:2023-12-03 11:55:30 27 4
gpt4 key购买 nike

我一直在环顾四周,但我找不到我真正需要的东西,尤其是对于UDP。

我正在尝试使基本的syslog服务器在端口514(UDP)上监听。

我一直在遵循Microsoft在MSDN上的指南:https://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive(v=vs.110).aspx

它没有明确说明(或者我是盲目的)如何重新打开连接以接收更多数据包。

这是我的代码(与链接基本相同)

     static void Main(string[] args)
{
try
{
ReceiveMessages();

Console.ReadLine();

}catch(SocketException ex)
{
if(ex.SocketErrorCode.ToString() == "AddressAlreadyInUse")
{
MessageBox.Show("Port already in use!");
}
}

}

public static void ReceiveMessages()
{
// Receive a message and write it to the console.



UdpState s = new UdpState();

Console.WriteLine("listening for messages");
s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
RecieveMoreMessages(s);
}

public static void RecieveMoreMessages(UdpState s)
{
s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
}

public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

Byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);

Console.WriteLine("Received: {0}", receiveString);
}

我尝试了重复,但是在2次事务处理后,我从套接字遇到“缓冲区空间用尽”错误。

有任何想法吗?

最佳答案

如果您坚持使用过时的APM模式,则需要使ReceiveCallback发出下一个BeginReceive调用。

由于UDP是无连接的,异步IO似乎毫无意义。可能您应该只使用一个同步接收循环:

while (true) {
client.Receive(...);
ProcessReceivedData();
}

删除所有异步代码。

如果您坚持使用异步IO,请至少使用 ReceiveAsync

关于c# - 多个客户端的C#.NET UDP套接字异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31500217/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com