I am developing an application for chatting. I have a probl开发者_开发技巧em. How can I detect a specific client over server?
I am using ServerSocket
and Socket
classes for communication.
Use getInetAddress()
of Socket
to get clients address.
Socket clientSocket = server.accept();
InetAddress clientAddress = clientSocket.getInetAddress();
If you have clients are unique to a given ip address, you can do clientAddress.getHostAddress()
to get the client's ip address.
A standard approach when a client connects to a server is to send a username and password to identify a client. If you want this to be transparent you can use System.getProperty("user.name")
which is simple but not very secure.
I'll just give a rough gist and improve on it later, but here goes:
Overview:
So you store some details on the server, and then when the client connects it sends a username and password and authenticates against these details. You store the endpoint Socket
in a map which is String username -> Socket socket
. Also store the reverse, Socket socket -> String username
. Use that to locate the username when you receive something from the socket. Even if you use socket channels, you can still get the socket from the channel using channel methods.
For managing these connections with NIO:
What I didn't talk about was how you'd receive the username / password data in the first place. For this, I advise framing. Read the data size, and then read the type of data, which should be two integers. You can write objects directly to the socket stream and process them in the same order on the other end.
You should use a selector with selector keys, and store received data in buffers attached to these selection keys. Then you just keep selecting and adding received data to the buffer if the socket is readable, while trying to process the buffer. If the buffer has useful data after a write to it from a read (i.e., you received the size of the data as well as the full data length), you need to remove the data and compact the buffer -- i.e., move the buffer position up by data length size (size of int) + data type size (size of int) + data length and then blit the entire lot down to 0 and set the position to the end of the current received data. Use buffer.compact()
for this.
I'd really advise something like KryoNet to do the hard work. Network programming is hard. But this might be for an assignment, so...
精彩评论