对 C# 中 UDP 协议的套接字感到困惑
我刚刚开始通过各种 Google 搜索学习套接字,但在弄清楚如何在 C# 中正确使用套接字时遇到一些问题,我需要一些帮助。
我有一个测试应用程序(Windows 窗体)和一个不同的类(实际上在它自己的 .dll 中,但这无关紧要)我有我的套接字代码的所有服务器/客户端代码。
问题 1)
在我的测试应用程序的服务器部分,用户可以单击“开始侦听”按钮,我的套接字应用程序的服务器部分应该开始侦听指定地址和端口上的连接,到目前为止,一切都很好。
但是,该应用程序将被阻止,并且在有人连接到服务器之前我无法执行任何操作。如果没有人连接怎么办?我该怎么处理?我可以指定接收超时,但那又怎样呢?它抛出异常,我该怎么办?我想要的是在主应用程序上进行某种活动,以便用户知道应用程序没有冻结并且正在等待连接。但如果没有建立连接,它应该超时并关闭所有内容。
也许我应该使用异步调用来发送/接收方法,但它们看起来很混乱,我无法使其工作,只能同步工作(我将在下面发布我当前的代码)。
问题 2)
当某些发送/接收调用超时时,我是否需要关闭任何内容。正如您将在我当前的代码中看到的那样,我在套接字上有一堆关闭,但这感觉不太对劲。但当操作超时并且我没有关闭套接字时,感觉也不对劲。
总结我的两个问题......我想要一个不会阻塞的应用程序,以便用户知道服务器正在等待连接(例如带有一点选框动画)。如果一段时间后从未建立连接,我想关闭所有应该关闭的东西。当建立连接或者在一段时间后没有发生连接时,我想将结果通知主应用程序。
这是我的一些代码,其余的类似。 Packet
类是一个自定义类,代表我的自定义数据单元,目前它只是一堆基于 enum
的属性,具有将它们转换为字节并返回为字节的方法特性。
开始监听连接的函数是这样的:
public void StartListening(string address, int port) {
try {
byte[] bufferBytes = new byte[32];
if(address.Equals("0.0.0.0")) {
udpSocket.Bind(new IPEndPoint(IPAddress.Any, port));
} else {
udpSocket.Bind(new IPEndPoint(IPAddress.Parse(address), port));
}
remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int numBytesReceived = udpSocket.ReceiveFrom(bufferBytes, ref remoteEndPoint);
if(numBytesReceived == 0) {
udpSocket.Close();
return;
}
Packet syncPacket = new Packet(bufferBytes);
if(syncPacket.PacketType != PacketType.Control) {
udpSocket.Close();
return;
}
} catch {
if(udpSocket != null) {
udpSocket.Close();
}
}
}
我确信我有一堆不必要的代码,但我对此很陌生,我不确定要做什么,是否有任何帮助修复我的代码以及如何解决上述问题真的很感激。
编辑:
我可能应该声明我的要求是使用UDP并自己在应用层实现这些东西。您可以将其视为家庭作业,但我没有标记为这样,因为代码不相关,不会成为我成绩的一部分,而且我的问题(我的问题)是“如何编码”,因为我的套接字经验很少,而且不是教过。
不过,我必须说,我现在解决了我的问题,我想...我在演示应用程序上使用线程,这给我带来了一些问题,现在我在协议连接中使用它,更有意义,我可以轻松更改我的自定义协议类属性并从演示应用程序中读取这些属性。
我指定了一个超时,如果达到超时则抛出 SocketException。每当捕获到这样的异常时,套接字连接就会关闭。我只是说连接握手,仅此而已。如果没有捕获到异常,则代码可能会顺利进行并建立连接。
请相应地调整您的答案。现在,我将其中任何一个标记为已接受的答案都没有意义,希望您理解。
I've just started learning Sockets through various Google searches but I'm having some problems figuring it out how to properly use Sockets in C# and I'm in the need of some help.
I have a test application (Windows Forms) and on a different class (which is actually in it's own .dll, but that's irrelevant) I have all the server/client code for my sockets code.
Question 1)
On my test application, on the server part, the user can click the "start listening" button and the server part of my sockets application should start listening for connections on the specified address and port, so far so good.
However, the application will be blocked and I can't do anything until someone connects to the server. What if no one connects? How should I handle that? I could specify a receive timeout but what then? It throws an exception, what can I do with that? What I would like is to have some sort of activity on the main application so the user knows the application didn't froze and is waiting for connections. But if a connection doesn't come, it should timeout and close everything.
Maybe I should use asynchronous calls to send/receive methods but they seem confusing and I was not able to make it work, only synchronous work (I'll post my current code below).
Question 2)
Do I need to close anything when some send/receive call times out. As you'll see on my current code, I have a bunch of closes on the socket, but this doesn't feel right somehow. But it also doesn't feel right when an operation times out and I don't close the socket.
In conclusion of my two questions.... I would like an application that doesn't block so the user knows the server is waiting for a connection (with a little marquee animation for instance). If a connection is never established after a period of time, I want to close everything that should be closed. When a connection is established or if it doesn't happen after a period of time, I would like to inform the main application of the result.
Here's some of my code, the rest is similar. The Packet
class is a custom class that represents my custom data unit, it's just a bunch of properties based on enums
for now, with methods to convert them to bytes and back into properties.
The function that starts to listen for connections is something like this:
public void StartListening(string address, int port) {
try {
byte[] bufferBytes = new byte[32];
if(address.Equals("0.0.0.0")) {
udpSocket.Bind(new IPEndPoint(IPAddress.Any, port));
} else {
udpSocket.Bind(new IPEndPoint(IPAddress.Parse(address), port));
}
remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int numBytesReceived = udpSocket.ReceiveFrom(bufferBytes, ref remoteEndPoint);
if(numBytesReceived == 0) {
udpSocket.Close();
return;
}
Packet syncPacket = new Packet(bufferBytes);
if(syncPacket.PacketType != PacketType.Control) {
udpSocket.Close();
return;
}
} catch {
if(udpSocket != null) {
udpSocket.Close();
}
}
}
I'm sure that I have a bunch of unnecessary code but I'm new at this and I'm not sure what do, any help fixing up my code and how to solve the issues above is really appreciated.
EDIT:
I should probably have stated that my requirements are to use UDP and implement these things myself in the application layer. You can consider this as homework but I haven't tagged as such because the code is irrelevant and will not be part of my grade and my problem (my question) is in "how to code" as my Sockets experience is minimal and it's not taught.
However I must say that I solved my problem for now I think... I was using threading on the demo application which was giving me some problems, now I'm using it in the protocol connections, makes more sense and I can easily change my custom protocol class properties and read those from the demo application.
I have specified a timeout and throw a SocketException if it reaches the timeout. Whenever an exception like this is caught, the socket connection is closed. I'm just talking about the connection handshake, nothing more. If no exceptions are caught, the code probably went smooth and the connection is established.
Please adapt your answers accordingly. Right now it doesn't make sense for me to marky any of them as the accepted answer, hope you understand.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的事情有点不对劲。
首先,UDP是无连接的。您不连接或断开连接。您所做的只是发送和接收(每次都必须指定目的地)。您还应该知道 UDP 唯一承诺的是每次读取时都会收到完整的消息。 UDP 不保证您的消息按正确的顺序到达或完全到达。
另一方面,TCP 是基于连接的。您连接、发送/接收,最后断开连接。 TCP 是基于流的(而 UDP 是基于消息的),这意味着您可以在第一次读取时获得一半消息,在第二次读取时获得另一半消息。 TCP 向您保证一切都会按正确的顺序到达(或者会尝试失败;)。因此,使用 TCP 意味着您应该拥有某种逻辑来知道完整消息何时到达,以及用于构建完整消息的缓冲区。
下一个大问题是关于阻塞。由于您是新手,因此我建议您使用线程来处理套接字。将侦听器套接字放在一个线程中,将每个连接套接字放在一个单独的线程中(5 个连接的客户端 = 5 个线程)。
我还建议您使用 TCP,因为构建完整的消息比排序消息和构建事务系统更容易(如果您想确保所有消息到达/来自客户端,则需要该系统)。
更新
你的UDP仍然是错误的。关闭除了清理系统资源之外不做任何事情。你应该这样做:
看到了吗?由于没有连接,关闭 UDP 套接字以开始侦听另一个套接字只是浪费时间。同一个套接字可以从所有知道正确端口和地址的 udp 客户端接收数据。这就是
remoteEndPoint
的用途。它告诉哪个客户端发送消息。更新 2
小更新,总结我的所有评论。
UDP 是无连接的。您永远无法检测连接是否已建立或断开。 UDP 套接字上的 Close 方法只会释放系统资源。对
client.Close()
的调用不会通知服务器套接字(与 TCP 一样)。检查连接是否打开的最佳方法是创建 ping/pong 类型的数据包。即客户端发送 PING 消息,服务器用 PONG 响应。请记住,如果消息未到达,UDP 不会尝试重新发送消息。因此,在假设服务器已关闭之前,您需要重新发送 PING 几次(如果您没有收到 PONG)。
至于客户端关闭,您需要向服务器发送自己的消息,告诉它客户端将停止与服务器通信。为了可靠性,这里也是同样的情况,请继续重新发送 BYE 消息,直到收到回复。
恕我直言,如果您想要可靠性,则必须实现 UDP 事务系统。 SIP (google rfc3261) 是使用 UDP 上的事务的协议示例。
You have got stuff a bit wrong.
First of all, UDP is connection-less. You do not connect or disconnect. All you do is to send and receive (must specify destination each time). You should also know that the only thing UDP promises is that a complete message arrives on each read. UDP do not guarantee that your messages arrive in the correct order or that they arrive at all.
TCP on the other hand is connection-based. You connect, send/receive and finally disconnect. TCP is stream-based (while UDP is message-based) which means that you can get a half message in the first read and the other half at the second read. TCP promises you that everything will arrive and in the correct order (or will die trying ;). So using TCP means that you should have some kind of logic to know when a complete message has arrived and a buffer that you use to build the complete message.
The next big question was about blocking. Since you are new at this, I recommend that you use Threads to handle sockets. Put the listener socket in one thread and each connecting socket in a separate thread (5 connected clients = 5 threads).
I also recommend that you use TCP since it's easier to build complete messages than ordering messages and build a transaction system (which will needed if you want to make sure that all messages arrives to/from clients).
Update
You still got UDP wrong. Close doesn't do anything other than cleaning up system resources. You should do something like this instead:
See? since there are no connection it's just waste of time to close a UDP socket to start listening from another one. The same socket can receive from ALL udp clients that know the correct port and address. That's what the
remoteEndPoint
is for. It tells which client that send the message.Update 2
Small update to make a summary of all my comments.
UDP is connectionless. You can never detect if a connection have been established or disconnected. The Close method on a UDP socket will only free system resources. A call on
client.Close()
will not notify the server socket (as it will with TCP).The best way to check if a connection is open is to create a ping/pong style of packet. i.e. the client sends a PING message and the server responds with a PONG. Remember that UDP will not try to resend your messages if they do not arrive. Therefore you need to resend the PING a couple of times before assuming that the server is down (if you do not receive a PONG).
As for clients closing you need to send your own message to the server telling it that the the client is going to stop talking to the server. For reliability the same thing goes here, keep resending the BYE message until you receive a reply.
imho it's mandatory that you implement a transactional system for UDP if you want reliability. SIP (google rfc3261) is an example of a protocol which uses transactions over UDP.
根据您的描述,我觉得您应该使用 TCP 套接字而不是 UDP。区别在于
TCP - 您等待特定 IP:端口上的连接,某些用户可以连接到它,直到套接字关闭为止,可以通过发送和接收信息进行通信。这就像打电话给某人一样。
UDP - 您在某个 IP:端口等待消息。用户想要通信只需通过UDP发送消息即可。您将通过 UDP 接收消息。不保证交货顺序。这更像是向某人发送一封蜗牛邮件。没有建立专用的通信通道。
现在来解决您的问题:
服务器
客户端
From your description I feel you should use TCP sockets instead of UDP. The difference is
TCP - You wait for a connection at a particuler IP:Port some user can connect to it and until the socket is closed can communicate by sending and receiveing information. This is like calling someone on phone.
UDP - you wait for a message at some IP:Port. User who wants to communicate just sends a message through UDP. You will receive the message through UDP. The order of delivery is not guaranteed. This is more like sending a snail mail to someone. There is no dedicated communication channel established.
Now coming to your problem
Server
Client