【发布时间】:2015-07-19 10:29:42
【问题描述】:
我一直在四处寻找,但我真的找不到我需要的东西,尤其是对于 UDP。
我正在尝试创建一个基本的 syslog 服务器侦听端口 514 (UDP)。
我一直在关注微软在 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 次事务后我遇到了来自套接字的“缓冲区空间不足”错误。
有什么想法吗?
【问题讨论】: