客户端服务器交互问题

发布于 2024-10-17 05:45:40 字数 373 浏览 7 评论 0原文

我正在尝试通过常规 TCP 协议在 java 中实现一个最小的聊天服务器。聊天服务器将侦听特定端口。我的问题是,如果有多个客户端向同一端口发送消息,如果消息不包含客户端的 IP 地址或目标名称,服务器能否区分客户端并单独响应每个客户端?

为了让我的问题更清楚一点,假设服务器收到一个数据包,其中仅包含

 "user: abc to-user:efg message:"Hello""

Can I find out in java the client who send the packet and returns back to the same address 或者我需要在其中包含一些标识符消息本身如“sender-ip = 1.1.1.1”

I am trying to implement a minimal chat server in java over regular TCP protocol. The chat server will listen on a specific port. The question I have is if there are multiple clients sending messages to the same port, can the server distinguish between the clients and respond to each individually if the messages do not contain the IP address or destination name of the client?

to make my question a bit more clear, suppose the server gets a packet that contains only

 "user: abc to-user:efg message:"Hello""

Can I find out in java the address of the client who sent the packet and respond back to the same address or will I need to include some identifier in the message itself like "sender-ip = 1.1.1.1"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

不羁少年 2024-10-24 05:45:41

多个客户端永远不会通过同一端口发送数据。您的客户端只有在连接到服务器时才会通过同一端口进行通信。在服务器中,每当 ServerSocket 接收到连接时,它都会返回一个新的 Socket。该套接字是以下各项的组合:服务器 IP+服务器端口和客户端 IP+客户端端口。每个套接字的服务器 IP 和服务器端口都是相同的;不同的是客户端 IP 和端口。通常,此套接字会传递给新线程以进行进一步通信,而 ServerSocket 返回侦听传入连接。获得对套接字的引用后,您可以调用 socket..getInetAddress().getHostAddress() 来获取远程 IP,并调用 socket.getPort() 来获取端口各自客户的。

Multiple clients will never send data over the same port. The only time your clients will talk over the same port is when they will connect to the server. In the server, whenever the ServerSocket receives a connection it returns a new Socket. This socket is a combination of the following : Server IP+ServerPort and Client IP+Client Port. The Server IP and the Server Port will be same for each socket; what differs is the client IP and Port. Usually this socket is passed to a new thread for further communication while the ServerSocket goes back to listen to incoming connections. Once you have a reference to the socket you can call socket..getInetAddress().getHostAddress() to get the remote IP and socket.getPort() to get the port of the respective client.

盛夏已如深秋| 2024-10-24 05:45:41

是的,每个连接都是独立的 - 每个连接都有不同的流可供读取。不过,您可以将相关的用户信息与连接相关联。

Yes, each connection will be separate - you'll have a different stream to read from for each connection. It's up to you to associate the relevant user information with the connection though.

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