欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Socket 客户端不显示的关闭连接服务端read一直阻塞 ServerSocket 

程序员文章站 2022-07-15 13:57:19
...

初次学习socket,写了下面例子

public class SocketServer {

	public static void main(String[] args) {
		int port = 8089;
		ServerSocket server = null;
		InputStream in = null;
		Socket socket = null;
		try {
			server = new ServerSocket(port);
			System.out.println("server:服务端启动,端口 "+port);
			socket = server.accept();
			in = socket.getInputStream();
			byte[] b = new byte[1024];
			int n = 0;
			StringBuilder sb = new StringBuilder();
			while((n=in.read(b))!=-1){
				sb.append(new String(b,0,n));
			}
			System.out.println("server:我收到客户的msg-"+sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(in !=null){
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(socket != null){
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(server !=null){
				try {
					server.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		

	}

}

 

public class SocketClient {

	public static void main(String[] args) {
		Socket socket = null;
		int port = 8089;
		String host ="127.0.0.1";
		OutputStream out = null;
		try {
			socket = new Socket(host,port);
			System.out.println("client:我连接上了服务端");
			out = socket.getOutputStream();
			out.write("你好".getBytes());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				Thread.sleep(10000);
				if(out != null){
					try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(socket != null){
					try {
						socket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		
		}
		

	}

}

 发现,当在客户端不close 相关的socket或输出流,服务端read会提示java.net.SocketException: Connection reset异常,这是由于client退出但是没有关闭连接导致。

当然,socket.shutdownOutputStream() 可以提示服务端,发送完成而不阻塞read

 

相关标签: ServerSocket