.NET 中的 UDP 套接字客户端

发布于 2024-08-27 20:06:33 字数 620 浏览 4 评论 0原文

我在客户端应用程序中使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九歌凝 2024-09-03 20:06:33

您可以在调用 ReceiveFrom() 之前使用 socket.Available() 来确定是否有任何等待数据。不过,理想情况下,您应该考虑使用 BeginReceiveFrom() 及其异步朋友将输入处理外包给其他线程。

You could use socket.Available() to determine if there is any waiting data before calling ReceiveFrom(). Ideally, though, you should consider farming out input handling to other threads using BeginReceiveFrom() and its asynchronous friends.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文