TCP:传输控制协议
-
特点:面向连接、可靠通信
-
TCP的最终目的:要保证在不可靠的信道上实现可靠的传输
-
TCP主要有三个步骤实现可靠传输:三次握手建立连接,传输数据进行确认,四次挥手断开连接
-
三次握手建立可靠连接。
-
建立连接后会建立可靠的通信管道
-
四次握手断开连接
-
TCP通信之客户端开发
客户端发送信息:
import java.io.*;
import java.net.*;public class TCPClient {public static void main(String[] args) {final String serverAddress = "127.0.0.1"; // 服务器地址final int serverPort = 8080; // 服务器端口try {// 连接到服务器Socket socket = new Socket(serverAddress, serverPort);System.out.println("Connected to server.");// 发送消息到服务器sendMessage(socket, "Hello, Server!");// 接收服务器的响应String response = receiveMessage(socket);System.out.println("Response from server: " + response);// 关闭连接socket.close();} catch (IOException e) {e.printStackTrace();}}private static void sendMessage(Socket socket, String message) throws IOException {PrintWriter out = new PrintWriter(socket.getOutputStream(), true);out.println(message);}private static String receiveMessage(Socket socket) throws IOException {BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));return in.readLine();}
}
TCP通信之服务端开发
服务端接收信息
import java.io.*;
import java.net.*;public class TCPExample {public static void main(String[] args) {final int PORT = 8080;try {// 启动服务器ServerSocket serverSocket = new ServerSocket(PORT);System.out.println("Server started. Waiting for connections...");// 等待客户端连接Socket clientSocket = serverSocket.accept();System.out.println("Client connected: " + clientSocket);// 处理客户端请求handleClient(clientSocket);// 关闭服务器serverSocket.close();} catch (IOException e) {e.printStackTrace();}}public static void handleClient(Socket clientSocket) {try {// 接收客户端消息BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));String message = in.readLine();System.out.println("Received message from client: " + message);// 向客户端发送响应PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);out.println("Hello, Client!");// 关闭连接clientSocket.close();} catch (IOException e) {e.printStackTrace();}}
}