In the following class SocketServidor
I send a single thread with the out
and the in
, but the class is supposed to be able to send two threads when it runs.
You're supposed to do this:
The server should work in multithreading, having for each active connection two threads, which we will call in and out:
- in for receiving client messages (input stream) This thread is blocked waiting for messages from the client. Messages that the server receives should be stored in a memory structure. When a given user has new messages, if this is online, the thread out associated with your connection should be notified in order to process the delivery of the messages.
- out for delivery of messages and notifications to customers (output stream) This thread is on hold, making it active when there are new messages or delivery notifications for the connection user.
SocketServidor
public class SocketServidor extends Thread{
private ServerSocket servidorSocket;
private Socket socket;
private static final int PORTA = 8080;
//HashMap recurso partilhado! (sempre que invocarmos este recurso temos de fazer synchronized)
private Map<String, ObjectOutputStream> utilizadores = new HashMap<String, ObjectOutputStream>(); //utilizadores da aplicacao (online!)
public SocketServidor(){
try {
servidorSocket = new ServerSocket(PORTA);
System.out.println("Estabelecer ligação TCP/IP no porto: " + PORTA);
System.out.println("A aguardar conexão do cliente...");
while(true){
socket = servidorSocket.accept();
new Thread(new ListennerSocket(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}