网络编程.ServerSocket与Socket通信

本文详细介绍了Java中使用ServerSocket和Socket进行网络通信的过程,包括服务端监听和客户端发送数据的具体实现,以及如何正确关闭各种流和Socket连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网络编程.ServerSocket与Socket通信

0.服务端

public class NBServer {

	public static void main(String[] args) {
		doServer();
	}
	/**
	 * 服务端监听
	 */
	public static void doServer() {
		ServerSocket server = null;
		Socket socket = null;
		InputStream is = null;
		OutputStream os = null;
		try {
			server = new ServerSocket(6666);
			while ((socket = server.accept()) != null) {
				is = socket.getInputStream();
				byte[] by = new byte[1024];
				int len = 0;
				while ((len = is.read(by)) != -1) {//is.read(by)最多读取by的长度,第二循环从下标0覆盖再读
					System.out.println(new String(by, 0, len));//所以每次从0到len为有效数据
				}
				socket.shutdownInput();// 单方向的关闭流  连接并未关闭

				os = socket.getOutputStream();
				os.write("ok ig nb".getBytes());
				os.flush();// 刷新立即输出
				socket.shutdownOutput();// 单方向的关闭流
			 }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(os);
			close(is, socket);//is.close()或者os.close(),会直接关闭socket
			close(server);
		}
		
	}
	/**
	 * 关闭ServerSocket
	 */
	public static void close(ServerSocket server) {
		if (server != null) {
			try {
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 关闭输入
	 */
	public static void close(InputStream is) {
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 关闭输出
	 */
	public static void close(OutputStream os) {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 关闭资源
	 */
	public static void close(InputStream is, Socket socket) {
		close(is);
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

1.客户端

public class NBClient {

	public static void main(String[] args) {
		doClient();
	}
	/**
	 * 客户端发送
	 */
	public static void doClient() {
		InputStream is = null;
		OutputStream os = null;
		Socket socket = null;
		try {
			socket = new Socket("localhost", 6666);//获取ip对应socket
			os = socket.getOutputStream();
			os.write("out stream".getBytes());
			os.flush();
			socket.shutdownOutput();// 单方向的关闭流
			
			is = socket.getInputStream();//读取流
			byte[] by = new byte[1024];
			int len = 0;
			while((len = is.read(by)) !=  -1) {
				System.out.println(new String(by, 0, len));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}  finally {
			NBServer.close(is, os, socket);
		}
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值