使用 TCP 建立交互方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ththcc/article/details/86503617

Client:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ClientDemo {
	public static void main(String[] args) throws IOException {
		/**
		 * Tcp传输,客户端建立的过程。
		 * 1、创建tcp客户端的socket服务。
		 * 	建议该对象一创建就明确目的地。要连接的主机
		 * 2、如果连接建立成功,说明数据传输通道已建立。
		 * 该通道就是socket流,是底层建立好的。既然是流,说明这里既有输入,又有输出。
		 * 可以通过getOutputStream(),和getInputStream()来获取两个字节流。
		 * 3、使用输出流,将数据写出。
		 * 4、关闭资源。
		 */
		
		//创建客户端socket服务。
		Socket socket = new Socket("127.0.0.1",10002);
		
		//获取socket流中的输出流。
		OutputStream out = socket.getOutputStream();
		
		//使用输出流将指定的数据写出去。
		out.write("tcp演示:哥们又来了!".getBytes());
		
		//读取服务端返回的数据,使用socket读取流
		InputStream in = socket.getInputStream();
		
		byte[] buf = new byte[2018];
		int len = in.read(buf);
		String text = new String(buf, 0, len);
		
		System.out.println(text);
		
		//关闭资源
		socket.close();
	}
}

Server:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
	public static void main(String[] args) throws IOException {
		// 服务端接收客户端发送过来的数据,并打印在控制台上。
		/**
		 * 建立tcp服务端的思路:
		 * 1、创建服务器端socket服务。通过ServerSocket对象。
		 * 2、服务端必须对外提供一个端口,否则客户端无法连接。
		 * 3、获取连接过来的客户端对象。
		 * 4、通过客户端对象获取socket流读取客户端发来的数据	
		 * 5、关闭资源。关客户端,关服务端。
		 */
		ServerSocket serverSocket = new ServerSocket(10002);
		// 获取连接过来的客户端对象。
		Socket socket = serverSocket.accept();
		String ip = serverSocket.getInetAddress().getHostAddress();
		InputStream is = socket.getInputStream();

		byte[] buf = new byte[1024];
		int len = is.read(buf);
		String text = new String(buf, 0, len);
		System.out.println(ip + ":" + text);
		
		//使用客户端socket对象的输出流给客户端返回数据
		OutputStream os = socket.getOutputStream();
		os.write("收到".getBytes());
		
		socket.close();
		is.close();
		serverSocket.close();
	}
}

猜你喜欢

转载自blog.csdn.net/ththcc/article/details/86503617