1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| public class EchoServerReceiveThread extends Thread { private Socket socket; public EchoServerReceiveThread( Socket socket ) { this.socket = socket; } @Override public void run() { InetSocketAddress remoteSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
int remoteHostPort = remoteSocketAddress.getPort(); String remoteHostAddress = remoteSocketAddress.getAddress().getHostAddress(); consoleLog("connected from "+ remoteHostAddress); try { InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); while (true) { String message = br.readLine();
if (message == null) { consoleLog("disconnection by client"); break; }
consoleLog(" received : " + message);
pw.println(message); }
} catch (SocketException e) { consoleLog("sudden closed by client");
} catch (IOException e) { e.printStackTrace(); } finally { try { if (socket != null && socket.isClosed() == false) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } private void consoleLog(String log) { System.out.println("[Server: "+getId() + "]" + log);
}
}
|