views:

61

answers:

3

was planning to create a server thread with a login (accepts new clients and creates threads that would handle them) and logout methods. login method will be blocked by socket.accept() method to wait for clients. would other clients who want to logout be able to call the logout method on the server thread, if the server thread is blocked by the other method?

+1  A: 

No. If a thread is blocked, the only way for it to do any additional processing is by waking up and continuing execution.

That said, other client threads can call a logout method that manipulates a shared data structure from their own thread. You may want to look into concurrency approaches for this, or using NIO and non blocking IO on the server thread.

SB
+1  A: 

A thread is a flow of execution. You have multiple of these here. Connection accepting thread is blocked in the accept(). If I understand you correctly, "client" threads are already started and are handling conversations with connected clients. I am guessing by "call the logout method on the server thread" you really mean "call a logout() method on the class, that also has the login() method". Since the "client" threads will be doing this, it should be OK, unless login() and logout() are not fighting for the same lock somewhere.

Nikolai N Fetissov
A: 

I think you should use accept in a thread that would just create a ThreadHandler and add this connection to it, the ThreadHandle is another Thread that will login the user and then do whatever you want more.

I have a code like this for a chat server:

while(true)
{
Socket clientSocket = server.accept();
ClientThreadHandler c = new ClientThreadHandler(clientSocket);
server.addClientThread(c);
}

The handler would now try to authenticate the client.

Also would be good to implement a heartbeat in which the server would send a packet to the connected and authenticated client, checking if the client still up. If not, server would close the connection. The ThreadHandler would be always listenning for client requisitions and treating them. Dont forget to synchronize methods that would be accessed from different threads.

fredcrs