赞
踩
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();
- }
- }
-
服务端接收信息
- 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();
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。