.NET 中的 UDP 套接字客户端
我在客户端应用程序中使用 UDP Sokckts。 以下是一些代码片段:
SendIP = new IPEndPoint(IPAddress.Parse(IP), port);
ReceiveIP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
socket.Bind(ReceiveIP);
接收 (while(true)):
byte[] data = new byte[BUFFERSIZE];
int receivedDataLength = socket.ReceiveFrom(data, ref ReceiveIP);
string s= Encoding.ASCII.GetString(data, 0, receivedDataLength);
我在接收时执行无限 while 操作,即使没有收到任何内容,同时还有其他事情要做。我想检查是否有实际上有可用数据,然后接收,否则不要等待。请注意,当前的接收方法会等待服务器发送消息。
I use UDP Sokckts in my client application.
Here are some code snippets:
SendIP = new IPEndPoint(IPAddress.Parse(IP), port);
ReceiveIP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
socket.Bind(ReceiveIP);
And to Receive (while(true)):
byte[] data = new byte[BUFFERSIZE];
int receivedDataLength = socket.ReceiveFrom(data, ref ReceiveIP);
string s= Encoding.ASCII.GetString(data, 0, receivedDataLength);
I am doing an infinite while on the receive, there are other things to be done in the while, even if nothing is received.. I want to check if there are actually available data then receive else do not wait. Note the current receive method waits until the server sends a message.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在调用
ReceiveFrom()
之前使用socket.Available()
来确定是否有任何等待数据。不过,理想情况下,您应该考虑使用 BeginReceiveFrom() 及其异步朋友将输入处理外包给其他线程。You could use
socket.Available()
to determine if there is any waiting data before callingReceiveFrom()
. Ideally, though, you should consider farming out input handling to other threads usingBeginReceiveFrom()
and its asynchronous friends.