Socket
Socket(套接字)就是两台主机之间逻辑连接的端点。
TCP/IP 协议是传输层协议,主要解决数据如何在网络中传输,而 HTTP 是应用层协议,主要解决如何包装数据。Socket 是通信的基石,是支持TCP/IP协议的网络通信的基本操作单元。它是网络通信过程中端点的抽象表示,包含进行网络通信必须得五种信息:连接使用的协议、本地主机的IP地址、本地进程的协议端口、远程主机的IP地址、远程进程的协议端口。
Socket流程
Socket 编程主要涉及客户端和服务端。服务端创建一个套接字(ServerSocket),并附加到一个端口上,服务器从这个端口监听连接。端口范围0~65536。客户端请求与服务器连接的时候,根据服务器的域名或IP地址加上端口号打开一个套接字。当服务器接受连接后,服务器和客户端之间的通信就像输入输出流一样进行操作。

Server:
public static void main(String[] args) throws IOException {
ExecutorService executorService = Executors.newCachedThreadPool();
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("server started");
while (true) {
Socket accept = serverSocket.accept();
executorService.execute(() -> handle(accept));
}
}
public static void handle(Socket socket) {
System.out.println("Thread ID:" + Thread.currentThread().getId()
+ " Thread Name:" + Thread.currentThread().getName());
try {
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int read = in.read(bytes);
System.out.println("Request: " + new String(bytes, 0, read));
OutputStream os = socket.getOutputStream();
os.write("Response: ".getBytes());
os.write(bytes, 0, read);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
public static void main(String[] args) {
try {
while (true) {
Socket socket = new Socket("127.0.0.1", 9999);
OutputStream os = socket.getOutputStream();
System.out.println("input please");
Scanner scanner = new Scanner(System.in);
String msg = scanner.nextLine();
os.write(msg.getBytes());
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int read = is.read(bytes);
System.out.println(new String(bytes, 0, read));
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
网友评论