UDP通信需要Java ServerSocket吗?
我在考试中遇到了以下问题:
“让我们假设您想要为客户端使用 UDP。您是否需要创建一个新的套接字来管理 UDP 中的并行连接?为什么或为什么不?如果多个客户端会发生什么情况连接到该套接字?”
该问题还引用了 Java 类 TCPServer.java
,它创建 ServerSocket,然后在 while(true)
循环中创建,它接受连接并为来自用户的传入连接请求创建套接字。
在我看来,TCP 服务器仅用于 TCP 连接,因此不可能对 UDP 客户端使用相同的服务器端代码。
I had following question on the exam:
"Let us assume that you want to use UDP for a client. Do you need to create a new socket for managing parallel connections in UDP? Why or why not? What happens if multiple clients connect to that socket?"
The question also referenced a Java class TCPServer.java
, which creates ServerSocket and later on in a while(true)
loop, it accepts connections and creates Sockets for incoming connection requests from users.
To my mind, TCP Server is only used for TCP connections, so it is not possible to use the same server side code for UDP client.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你走在正确的轨道上。
ServerSockets 用于 TCP 连接。 DatagramSockets(仍然是无连接的)用于UDP。
并回答另一部分,即“如果多个客户端连接到该套接字会发生什么?”答案是:
来回答“为什么或为什么不”的问题- UDP 是无连接的,因此不使用新的 Socket 进行通信。 UDP 仅接收 DatagramPacket,然后丢弃它(如果应用程序确定它无效、格式错误等),或者使用 DatagramPacket 进行回复。在 UDP 中,没有连接、没有连接状态、也没有输入/输出流。
You're on the right track.
ServerSockets are used for TCP connections. DatagramSockets (which are still connectionless) are used for UDP.
And to answer the other part, that is, "What happens if multiple clients connect to that socket?" the answer is:
To answer the "Why or why not" - UDP is connectionless, and therefore a new Socket isn't used for communication. UDP just receives a DatagramPacket, and either drops it (if the app determines that it's invalid, malformed, etc.), or it replies with a DatagramPacket. In UDP there's no connection, no connection state, and no input/output streams.
该问题要求您解释为什么或为什么不。因此,本质上,如果您不相信 ServerSocket 代码适用于 UDP,那么您必须说出原因。从你的最后一句话我相信你已经知道问题的答案了,现在你只需充满信心地写下来。
The question asked you to explain why OR why not. So in essence if you didn't believe that the ServerSocket code would work for UDP then you had to say why. From your last sentence I believe you know the answer to the question, now you just have to write it down with confidence.