C:Hello Server
Server 收到 Client 的訊息後
S:Hello Client
Client 收到 Server 的訊息後
C:Server I got it
以上是 HandShake 的過程。也就是建立 Connection 完成了。
那 .... 建立完 Connection 後,Server 掛掉,Client 會發生什麼事情呢?
public static int port = 8765; // port
Server 收到 Connection 後馬上取消 Connection
Client
寫資料給 Server,如果 Server 關閉時,這裡會跑到 Exception。
發現一件事情,讀取資料的時候不會進入 Exception,會進入 -1 進而讀取不到資料。
結果:
寫入資料會發生寫入錯誤。
結果:
Server Code:
public class Server extends Thread {public static int port = 8765; // portpublic static void main(String args[]) throws Exception {ServerSocket serverSocket = new ServerSocket(port); // create TCP SocketSystem.out.println("client not connect");Socket socket = serverSocket.accept(); //accept clientif (socket.isConnected()) {System.out.println("client connect");serverSocket.close();socket.close();}OutputStream os = socket.getOutputStream();os.write("Server HiHi ".getBytes("UTF-8"));// Send message to clientos.close(); //closesocket.close();System.out.println("Server write end");// }}}
Client Code:
public class Client {public static int port = 8765; // portpublic static void main(String args[]) {Socket client = null;try {client = new Socket("127.0.0.1", port);} catch (UnknownHostException e2) {e2.printStackTrace();} catch (IOException e2) {e2.printStackTrace();}try {Thread.sleep(10000);} catch (Exception e) {}InputStream in = null;try {in = client.getInputStream();} catch (Exception e) {System.out.println("inputStream exception");}OutputStream out = null;try {out = client.getOutputStream();} catch (Exception e) {System.out.println("outputStream exception");}writeData(out);System.out.println("hey");StringBuffer buffer = new StringBuffer(); // read stringtry {while (true) {int state = in.read(); // -1 mean endSystem.out.println("Read");if (state == -1) {break; // -1 mean no data so break}buffer.append((char) state);}} catch (Exception e) {System.out.println("Read Exception");try {in.close();} catch (IOException e1) {e1.printStackTrace();}}System.out.println(buffer + "0.0.."); // print server messagetry {client.close();} catch (IOException e) {e.printStackTrace();} }public static void writeData(OutputStream out) {try {System.out.println("Write");out.write(12123);} catch (IOException e) {System.out.println("Write Exception");e.printStackTrace();}}}