Search code examples
javasocketsserversocket

Java ServerSocket and Socket to implement an IM System


I'm trying to implement a small LAN IM System in Java. And I have a KDC(Key Distribution Center) for dispatching session keys to users. Here's a picture about my initial design: enter image description here
Steps about chatting with a logged-in user:
(Two users, A and B)
1. A send request to KDC says that he wants to talk with B
2. KDC forward request to B
3. B accepts or denies the request
4. If B accepts, KDC will send A's public key to B and B's public key to A, Else send null
5. A and B generate a secret key to chat with each other
Now my questions:
I use ServerSocket to implement KDC. It will manage and dispatch public keys. I use Socket to implement User, and I know how to let a User communicate with KDC but I don't know how to let a User communicate with another User. So I have to use both Socket and ServerSocket to implement User? And if A talks with two or more other users at the same time. How to deal with the sockets and server sockets in a User?


Solution

  • Obviously the server must push messages to users (the forwarded requests). Therefore, either the user keeps a permanent socket connection open to the server, or the user must be ready to accept new connections from the server.

    For the first option, you could route all messages between users via the server, i.e. much as the server negotiates the original requests, it also distributes the messages. Advantage: The infrastructure is relatively simple, you can handle requests and messages with the same logic, and distributing messages to multiple users is easy. Obvious disadvantage: The server becomes a bottleneck for all messages, and security-wise it will see all messages.

    The second option means that, yes, each User must have a ServerSocket in order to accept incoming connections, as well as initiating outgoing connections via Sockets. In this scenario, you must find a reliable way of negotiating who contacts whom. A natural solution would be to have the User which sends a chat request to also connect via a Socket to the ServerSocket of the other User. Advantage: Messages can pass directly between users. Disadvantage: Much more complicated infrastructure, especially when multiple users chat with each other. And it's not more failsafe than the centralized server solution, as it still requires the server for handling requests.