|
import java.io.*; |
|
import java.net.ServerSocket; |
|
import java.net.Socket; |
|
|
|
|
|
/** |
|
* Classe server del servizio Echo. Questa classe restituisce al client |
|
* qualsiasi stringa inviata. |
|
*/ |
|
public class EchoServer extends Thread { |
|
/** |
|
* Porta su cui il ServerSocket si lega. |
|
*/ |
|
private static final int PORT = 65500; |
|
|
|
/** |
|
* ServerSocket è un socket speciale, crea un nuovo Socket |
|
* ad ogni richiesta di connessione. |
|
*/ |
|
protected final ServerSocket serverSocket; |
|
|
|
/** |
|
* Il costruttore instanzia il ServerSocket su cui i client |
|
* effettueranno una richiesta di connessione. |
|
* @throws IOException |
|
*/ |
|
public EchoServer() throws IOException { |
|
this.serverSocket = new ServerSocket(PORT); |
|
start(); |
|
} |
|
|
|
/** |
|
* Nel corpo del metodo run() i passaggi sono semplici: |
|
* 1. Viene creato un socket ad ogni richiesta di connessione. |
|
* 2. Viene letto il messaggio spedito. |
|
* 3. Lo stesso messaggio viene rispedito al mittende. |
|
* 4. Il server si rimette in ascolto per eventuali nuove richieste. |
|
*/ |
|
public void run() { |
|
while (true) { |
|
try { |
|
/* |
|
serverSocket.accept() è una chiamata bloccante, ovvero |
|
il server rimmarrà bloccato su questa chiamata di procedura |
|
fintantoché non verrà effettuata una richiesta di connessione |
|
da parte di un client. |
|
*/ |
|
Socket clientSocket = serverSocket.accept(); |
|
/* |
|
I messaggi vengono scambiati tramite serializzazione di stringhe. |
|
Per semplicità viene usata questa strategia, bisogna notare che è |
|
possibile utilizzare qualsiasi classe Java che supporti la gestione |
|
di un InputStream. |
|
*/ |
|
ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream()); |
|
String message = (String) input.readObject(); // lettura del messaggio |
|
/* |
|
Vale come input. |
|
*/ |
|
ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream()); |
|
System.out.println(message); |
|
output.writeObject(message); |
|
output.flush(); |
|
// Richiesta gestita, poiché siamo in un ciclo infinito il server è pronto per gestire |
|
// una nuova connessione. |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} catch (ClassNotFoundException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
} |
|
|
|
public static void main(String[] args) { |
|
try { |
|
new EchoServer(); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
} |