32、Java——Socket通信

Socket通信

32、Java——Socket通信_第1张图片
32、Java——Socket通信_第2张图片
32、Java——Socket通信_第3张图片
32、Java——Socket通信_第4张图片

	@Test
	public void testSocketServer() throws IOException {
//		新建服务端socket,并设置启动端口
		ServerSocket serverSocket = new ServerSocket(8000);
		System.out.println("服务已在8000端口启动");
//		等待客户端连接
		Socket socket = serverSocket.accept();
		System.out.println("客户端已连接");
//		输入输出流
		InputStream inputStream = socket.getInputStream();
		OutputStream outputStream = socket.getOutputStream();
		for (int i = 0; i < 5; i++) {
			char c = (char) inputStream.read();
			System.out.print(c);
		}
		System.out.println();
		outputStream.write("world".getBytes());
		outputStream.flush();
//		关闭socket连接
		socket.close();
//		关闭服务,释放端口
		serverSocket.close();
	}

	@Test
	public void testSocketClient() throws IOException {
//		新建客户端socket
		Socket socket = new Socket("127.0.0.1", 8000);
//		输入输出流
		InputStream inputStream = socket.getInputStream();
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write("hello".getBytes());
		outputStream.flush();
		for (int i = 0; i < 5; i++) {
			char c = (char) inputStream.read();
			System.out.print(c);
		}
		System.out.println();
//		关闭socket连接
		socket.close();
	}

你可能感兴趣的:(Java基础,java,socket)