UDP 通信需要 Java ServerSocket? [英] Java ServerSocket required for UDP communication?

查看:47
本文介绍了UDP 通信需要 Java ServerSocket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在考试中有以下问题:

I had following question on the exam:

让我们假设您想为客户端使用 UDP.您是否需要创建一个新的套接字来管理 UDP 中的并行连接?为什么或为什么不呢?如果多个客户端连接到该套接字会发生什么?

该问题还引用了一个 Java 类 TCPServer.java,它创建 ServerSocket,稍后在 while(true) 循环中,它接受连接并为传入的创建套接字来自用户的连接请求.

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.

在我看来,TCP Server 仅用于 TCP 连接,因此不可能对 UDP 客户端使用相同的服务器端代码.

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.

推荐答案

您走在正确的轨道上.

ServerSockets 用于TCP 连接.DatagramSockets(仍然是无连接的)用于UDP.

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:

  1. 如果是 UDP,那就没问题,因为它是无连接的
  2. 如果是 TCP,那么 ServerSocket 应该看到连接请求,并创建一个新的 Socket 与该客户端进行双向通信

回答为什么或为什么不" - UDP 是无连接的,因此不使用新的 Socket 进行通信.UDP 只是接收到一个 DatagramPacket,然后丢弃它(如果应用程序确定它无效、格式错误等),或者它回复一个 DatagramPacket.在 UDP 中没有连接,没有连接状态,也没有输入/输出流.

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.

这篇关于UDP 通信需要 Java ServerSocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆