Reputation:
I'm trying to develop a Java chat server. I don't know if the better solution is to do either of:
Which is the best way to go for this situation?
Upvotes: 0
Views: 227
Reputation:
Actually you do not have to keep connection for eternity for each client ! All you have to do is store client's state server side and then communicate via any connection. Then you can get back resource and use them more wisely when your client doesn't seem to be active for a while.
Upvotes: 1
Reputation: 2757
i suggest you to learn Serialization
if you want to develop an application with UI support. Moreover, you have to create a socket for each client especially in Server
side. And a Server should have threads which maybe you can call client handler
, to deal with clients' requests. Query a database for checking received messages is meaningless but you can save all messages in a database maybe. My advice is if you are going to use a database (well i suggest that), use it for dealing with registration process of clients. So whenever a client sends a request to server for logging in, a thread will check will check if that client has already have an account or not in database.If not you can implement a simple register form. And logically every client will have a friend list
which you should keep them in a database.
EDIT: The Server will look like this.
public class Server {
public static void main(String[] args) {
try {
ServerSocket s = new ServerSocket(8087);
System.out.println("Server Started");
while (true) {
Socket incoming = s.accept();
System.out.println(incoming.getInetAddress().getHostAddress() + " was connected!");
new ClientHandler2(incoming).start();
}
} catch (Exception e) {}
}
}
So the main point is Server should never stop to listen the specified port.
Client Handler which is a thread created in Server side.
public class ClientHandler extends Thread {
private Socket incoming;
public ClientHandler(Socket incoming){
this.incoming = incoming;
}
@Override
public void run(){}
Server will send the initialized socket into the ClientHandler's constructor and call start()
method to run it.
Upvotes: 1