客户端服务器交互问题
我正在尝试通过常规 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
多个客户端永远不会通过同一端口发送数据。您的客户端只有在连接到服务器时才会通过同一端口进行通信。在服务器中,每当
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 newSocket
. 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 theServerSocket
goes back to listen to incoming connections. Once you have a reference to the socket you can callsocket..getInetAddress().getHostAddress()
to get the remote IP andsocket.getPort()
to get the port of the respective client.是的,每个连接都是独立的 - 每个连接都有不同的流可供读取。不过,您可以将相关的用户信息与连接相关联。
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.