TCP连接建立与终止

来源:互联网 发布:ubuntu安装spark 编辑:程序博客网 时间:2024/05/17 03:48

TCP连接建立与终止

客户端:

In.close();

Out.close();

Socket.close();

如果3个都不关闭的话则会出现:

 

第二中情况:

Out.close();

如果只关闭输出流,则会出现:


第三中情况:

In.close();

如果只关闭输入流则会出现:


第四中情况:

Socket.close();

如果只关socket则会出现:


测试代码:

服务端代码:

package com.zhou; import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket; public class TestTcpIp {     public static void main(String[] args) throws IOException {       ServerSocket server = new ServerSocket(9999);       System.out.println("服务器9999启动");       while (true) {           Socket socket = server.accept();           System.out.println("有客户端coming...");           TestTcpIp myServer = new TestTcpIp();           myServer.invock(socket);       }    }     public void invock( final Socket socket) {       new Thread(new Runnable() {           @Override           public void run() {              if (socket != null) {                  OutputStream out = null;                  InputStream in = null;                  try {                     in = socket.getInputStream();                     byte[] msg = new byte[1024];                     in.read(msg);                     System.out.println(new String(msg).trim());                     out = socket.getOutputStream();                     out.write("str\r\n".getBytes());                     out.flush();                  } catch (IOException e) {                     e.printStackTrace();                  }finally{                     try {                         //Thread.sleep(5000);                         //socket.close();//过5秒关闭服务端(发送服务端挥手)                     } catch (Exception e) {                         e.printStackTrace();                     }                  }              }           }       }).start();    }}


客户端代码:(手打可能有点小问题…)

Public class TestClient2{       Publicstatic void main(String args) throws Exception{       Socket socket = new Socket(“192.168.30.44”,9999);       BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream));       PrintWriter out – new PrintWriter(socket.getOutputStream());out.println(“fffffff”);out.flush();String str =in.readLine();       out.close();       in.close();       socket.close();}}


 

如果服务端过5秒关闭服务端的话,则挥手则会有4次:



 [u1]客户端没有关闭



 [u2]客户端输出流关闭,服务器收到客户端关闭


0 0