client server interaction question
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 t开发者_Python百科o the same address or will I need to include some identifier in the message itself like "sender-ip = 1.1.1.1"
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.
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.
精彩评论