Ho due programmini, a scopo didattico.
Il primo lavora come server, il secondo come client.
Il server fa un semplice "echo" dei messaggi che arrivano dal client, chiudendo però la socket se il messaggio che arriva è "BYE". Il problema è che il client non si accorge quando la socket è stata chiusa dal server e, se l'utente client continua ad inviare messaggi, NON viene lanciata alcuna eccezzione.
Vorrei chiedervi di aiutarmi a risolvere questo problema.
SERVER
codice:
package echoserver;
import java.io.*;
import java.net.*;
/**
* This program implements a simple server that listens to
* port 8189 and echoes back all client input.
*/
public class EchoServer {
public static void main(String[] args ) {
try {
// establish server socket
ServerSocket s = new ServerSocket(8189);
System.out.println("ECHO SERVER RUNNING...");
// wait for client connection
while(true) {
Socket incoming = s.accept();
System.out.println("Accepted connection from client");
BufferedReader s_in = new BufferedReader
(new InputStreamReader(incoming.getInputStream()));
PrintWriter s_out = new PrintWriter
(incoming.getOutputStream(), true /* autoFlush */);
s_out.println( "Hello! Enter BYE to exit." );
// echo client input
boolean done = false;
while (!done) {
String line = s_in.readLine();
s_out.println("Echo: " + line);
if (line.trim().equals("BYE"))
done = true;
}
incoming.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
CLIENT
codice:
package echoserver;
import java.net.*;
import java.io.*;
public class EchoClient {
public EchoClient() {
}
public static void main(String args[]) {
Socket s = null;
try{
String SERVER = "localhost";
int serverPort = 8189;
// s = new Socket(SERVER, serverPort); BLOCCANTE
s = new Socket();
s.connect(new InetSocketAddress(SERVER, serverPort),1000);
BufferedReader s_in = new BufferedReader
(new InputStreamReader(s.getInputStream()));
PrintWriter s_out = new PrintWriter(s.getOutputStream(), true /* autoFlush */);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String data = s_in.readLine();
System.out.println("Received:" + data) ;
while(true) {
String input = console.readLine();
s_out.println(input);
data = s_in.readLine();
System.out.println("Received:" + data) ;
}
}
catch (UnknownHostException e){
System.out.println("Sock:"+e.getMessage());
}
catch (EOFException e){System.out.println("EOF:"+e.getMessage());
}
catch (IOException e){
System.out.println("IO:"+e.getMessage());
}
finally {
if(s!=null)
try {s.close();}
catch (IOException e) {
System.out.println("close:"+e.getMessage());}}
}
}