网络协议分析-http/https/tcp/udp

news2025/1/21 1:05:21

文章目录

  • TCP三次握手/TCP三次挥手
    • TCP三次握手
    • TCP四次挥手
    • 完整报文
  • 实例代码
    • HttpSampleClient
    • HttpSampleServer
    • HttpsSampleClient
    • HttpsSampleServer
    • TcpSampleClient
    • TcpSampleServer
    • UdpSampleClient
    • UdpSampleSever
  • 资料

TCP三次握手/TCP三次挥手

“三次握手”的目的是“为了防止已失效的连接请求报文段突然又传送到了服务端,因而产生 错误”。主要目的防止 server 端一直等待,浪费资源。换句话说,即是为了保证服务端能收 接受到客户端的信息并能做出正确的应答而进行前两次(第一次和第二次)握手,为了保证客 户端能够接收到服务端的信息并能做出正确的应答而进行后两次(第二次和第三次)握手。

“四次挥手”原因是因为 tcp 是全双工模式,接收到 FIN 时意味将没有数据再发来,但是还是 可以继续发送数据。
在这里插入图片描述

TCP三次握手

在这里插入图片描述

TCP四次挥手

在这里插入图片描述

完整报文

# 三次握手:SYN=1 Seq=0
No.     Time           Source                Destination           Protocol Length Info
     50 7.055660280    127.0.0.1             127.0.0.1             TCP      74     4415612345 [SYN] Seq=0 Win=65495 Len=0 MSS=65495 SACK_PERM TSval=2731439096 TSecr=0 WS=128

Frame 50: 74 bytes on wire (592 bits), 74 bytes captured (592 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.312489778 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.312489778 seconds
    [Time delta from previous captured frame: 0.004110298 seconds]
    [Time delta from previous displayed frame: 0.000000000 seconds]
    [Time since reference or first frame: 7.055660280 seconds]
    Frame Number: 50
    Frame Length: 74 bytes (592 bits)
    Capture Length: 74 bytes (592 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP SYN/FIN]
    [Coloring Rule String: tcp.flags & 0x02 || tcp.flags.fin == 1]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 44156, Dst Port: 12345, Seq: 0, Len: 0

# 三次握手:SYN1 ACK=1 Seq=0
No.     Time           Source                Destination           Protocol Length Info
     51 7.055692471    127.0.0.1             127.0.0.1             TCP      74     1234544156 [SYN, ACK] Seq=0 Ack=1 Win=65483 Len=0 MSS=65495 SACK_PERM TSval=2731439096 TSecr=2731439096 WS=128

Frame 51: 74 bytes on wire (592 bits), 74 bytes captured (592 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.312521969 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.312521969 seconds
    [Time delta from previous captured frame: 0.000032191 seconds]
    [Time delta from previous displayed frame: 0.000032191 seconds]
    [Time since reference or first frame: 7.055692471 seconds]
    Frame Number: 51
    Frame Length: 74 bytes (592 bits)
    Capture Length: 74 bytes (592 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP SYN/FIN]
    [Coloring Rule String: tcp.flags & 0x02 || tcp.flags.fin == 1]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 12345, Dst Port: 44156, Seq: 0, Ack: 1, Len: 0

# 三次握手:Ack=1 Seq=1
No.     Time           Source                Destination           Protocol Length Info
     52 7.055725041    127.0.0.1             127.0.0.1             TCP      66     4415612345 [ACK] Seq=1 Ack=1 Win=65536 Len=0 TSval=2731439096 TSecr=2731439096

Frame 52: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.312554539 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.312554539 seconds
    [Time delta from previous captured frame: 0.000032570 seconds]
    [Time delta from previous displayed frame: 0.000032570 seconds]
    [Time since reference or first frame: 7.055725041 seconds]
    Frame Number: 52
    Frame Length: 66 bytes (528 bits)
    Capture Length: 66 bytes (528 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP]
    [Coloring Rule String: tcp]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 44156, Dst Port: 12345, Seq: 1, Ack: 1, Len: 0

# 客户端发送消息  Hello, server!.
No.     Time           Source                Destination           Protocol Length Info
     53 7.057834891    127.0.0.1             127.0.0.1             TCP      81     4415612345 [PSH, ACK] Seq=1 Ack=1 Win=65536 Len=15 TSval=2731439098 TSecr=2731439096

Frame 53: 81 bytes on wire (648 bits), 81 bytes captured (648 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.314664389 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.314664389 seconds
    [Time delta from previous captured frame: 0.002109850 seconds]
    [Time delta from previous displayed frame: 0.002109850 seconds]
    [Time since reference or first frame: 7.057834891 seconds]
    Frame Number: 53
    Frame Length: 81 bytes (648 bits)
    Capture Length: 81 bytes (648 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp:data]
    [Coloring Rule Name: TCP]
    [Coloring Rule String: tcp]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 44156, Dst Port: 12345, Seq: 1, Ack: 1, Len: 15
Data (15 bytes)

0000  48 65 6c 6c 6f 2c 20 73 65 72 76 65 72 21 0a      Hello, server!.

# 服务端应答
No.     Time           Source                Destination           Protocol Length Info
     54 7.057859991    127.0.0.1             127.0.0.1             TCP      66     1234544156 [ACK] Seq=1 Ack=16 Win=65536 Len=0 TSval=2731439098 TSecr=2731439098

Frame 54: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.314689489 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.314689489 seconds
    [Time delta from previous captured frame: 0.000025100 seconds]
    [Time delta from previous displayed frame: 0.000025100 seconds]
    [Time since reference or first frame: 7.057859991 seconds]
    Frame Number: 54
    Frame Length: 66 bytes (528 bits)
    Capture Length: 66 bytes (528 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP]
    [Coloring Rule String: tcp]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 12345, Dst Port: 44156, Seq: 1, Ack: 16, Len: 0

#  服务端发送消息 Server received: Hello, server!.
No.     Time           Source                Destination           Protocol Length Info
     55 7.059237157    127.0.0.1             127.0.0.1             TCP      98     1234544156 [PSH, ACK] Seq=1 Ack=16 Win=65536 Len=32 TSval=2731439100 TSecr=2731439098

Frame 55: 98 bytes on wire (784 bits), 98 bytes captured (784 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.316066655 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.316066655 seconds
    [Time delta from previous captured frame: 0.001377166 seconds]
    [Time delta from previous displayed frame: 0.001377166 seconds]
    [Time since reference or first frame: 7.059237157 seconds]
    Frame Number: 55
    Frame Length: 98 bytes (784 bits)
    Capture Length: 98 bytes (784 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp:data]
    [Coloring Rule Name: TCP]
    [Coloring Rule String: tcp]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 12345, Dst Port: 44156, Seq: 1, Ack: 16, Len: 32
Data (32 bytes)

0000  53 65 72 76 65 72 20 72 65 63 65 69 76 65 64 3a   Server received:
0010  20 48 65 6c 6c 6f 2c 20 73 65 72 76 65 72 21 0a    Hello, server!.

# 客户端还给了一个回应
No.     Time           Source                Destination           Protocol Length Info
     56 7.059273656    127.0.0.1             127.0.0.1             TCP      66     4415612345 [ACK] Seq=16 Ack=33 Win=65536 Len=0 TSval=2731439100 TSecr=2731439100

Frame 56: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.316103154 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.316103154 seconds
    [Time delta from previous captured frame: 0.000036499 seconds]
    [Time delta from previous displayed frame: 0.000036499 seconds]
    [Time since reference or first frame: 7.059273656 seconds]
    Frame Number: 56
    Frame Length: 66 bytes (528 bits)
    Capture Length: 66 bytes (528 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP]
    [Coloring Rule String: tcp]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 44156, Dst Port: 12345, Seq: 16, Ack: 33, Len: 0

# 四次挥手 1 FIN=1 Ack=33 Seq=16
No.     Time           Source                Destination           Protocol Length Info
     57 7.062253079    127.0.0.1             127.0.0.1             TCP      66     4415612345 [FIN, ACK] Seq=16 Ack=33 Win=65536 Len=0 TSval=2731439103 TSecr=2731439100

Frame 57: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.319082577 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.319082577 seconds
    [Time delta from previous captured frame: 0.002979423 seconds]
    [Time delta from previous displayed frame: 0.002979423 seconds]
    [Time since reference or first frame: 7.062253079 seconds]
    Frame Number: 57
    Frame Length: 66 bytes (528 bits)
    Capture Length: 66 bytes (528 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP SYN/FIN]
    [Coloring Rule String: tcp.flags & 0x02 || tcp.flags.fin == 1]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 44156, Dst Port: 12345, Seq: 16, Ack: 33, Len: 0

# 四次挥手 2 ACK=17 Seq=33
No.     Time           Source                Destination           Protocol Length Info
     58 7.110165407    127.0.0.1             127.0.0.1             TCP      66     1234544156 [ACK] Seq=33 Ack=17 Win=65536 Len=0 TSval=2731439151 TSecr=2731439103

Frame 58: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.366994905 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.366994905 seconds
    [Time delta from previous captured frame: 0.047912328 seconds]
    [Time delta from previous displayed frame: 0.047912328 seconds]
    [Time since reference or first frame: 7.110165407 seconds]
    Frame Number: 58
    Frame Length: 66 bytes (528 bits)
    Capture Length: 66 bytes (528 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP]
    [Coloring Rule String: tcp]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 12345, Dst Port: 44156, Seq: 33, Ack: 17, Len: 0

# 四次挥手: 3 Fin=1 Ack=17 Seq=33
No.     Time           Source                Destination           Protocol Length Info
     61 7.390471256    127.0.0.1             127.0.0.1             TCP      66     1234544156 [FIN, ACK] Seq=33 Ack=17 Win=65536 Len=0 TSval=2731439431 TSecr=2731439103

Frame 61: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.647300754 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.647300754 seconds
    [Time delta from previous captured frame: 0.000234452 seconds]
    [Time delta from previous displayed frame: 0.280305849 seconds]
    [Time since reference or first frame: 7.390471256 seconds]
    Frame Number: 61
    Frame Length: 66 bytes (528 bits)
    Capture Length: 66 bytes (528 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP SYN/FIN]
    [Coloring Rule String: tcp.flags & 0x02 || tcp.flags.fin == 1]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 12345, Dst Port: 44156, Seq: 33, Ack: 17, Len: 0

# 四次挥手 4 Ack=34 Seq=17
No.     Time           Source                Destination           Protocol Length Info
     62 7.390499061    127.0.0.1             127.0.0.1             TCP      66     4415612345 [ACK] Seq=17 Ack=34 Win=65536 Len=0 TSval=2731439431 TSecr=2731439431

Frame 62: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface lo, id 0
    Section number: 1
    Interface id: 0 (lo)
    Encapsulation type: Ethernet (1)
    Arrival Time: Aug 29, 2023 08:26:32.647328559 EDT
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1693311992.647328559 seconds
    [Time delta from previous captured frame: 0.000027805 seconds]
    [Time delta from previous displayed frame: 0.000027805 seconds]
    [Time since reference or first frame: 7.390499061 seconds]
    Frame Number: 62
    Frame Length: 66 bytes (528 bits)
    Capture Length: 66 bytes (528 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ethertype:ip:tcp]
    [Coloring Rule Name: TCP]
    [Coloring Rule String: tcp]
Ethernet II, Src: 00:00:00_00:00:00 (00:00:00:00:00:00), Dst: 00:00:00_00:00:00 (00:00:00:00:00:00)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 44156, Dst Port: 12345, Seq: 17, Ack: 34, Len: 0

实例代码

HttpSampleClient

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpSampleClient {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code:" + responseCode);
            // read content
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            System.out.println("Response Body: " + response);
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HttpSampleServer

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class HttpSampleServer {
    public static void main(String[] args) {
        try {
            // create http server to bind 8080
            HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 8080), 0);
            // bind path
            server.createContext("/", new MyHandler());
            server.start();
            System.out.println("Http Sever started on port 8080");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class MyHandler implements HttpHandler {
        // 设置响应头c
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = "Hello from the local HTTP server!";
            exchange.sendResponseHeaders(200, response.getBytes().length);

            // 获取输出流并写入响应内容
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}

HttpsSampleClient

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class HttpsSampleClient {
    public static void main(String[] args) {
        try {
            // Create and configure the SSL context
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }
            }}, new java.security.SecureRandom());

            // Create an SSL socket
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket("localhost", 12345);

            // Get input and output streams for secure communication
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // autoFlush

            // Send a message to the server
            String message = "Hello, server!";
            writer.println(message);

            // Read response from the server
            String serverResponse = reader.readLine();
            System.out.println("Server response: " + serverResponse);

            // Close resources
            reader.close();
            writer.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HttpsSampleServer

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.KeyStore;

public class HttpsSampleServer {
    public static void main(String[] args) {
        String keystorePath = "./keystore.jks";
        char[] keystorePassword = "flannery".toCharArray();

        try {
            // Load the keystore containing the server's SSL certificate
            KeyStore keystore = KeyStore.getInstance("JKS");
            keystore.load(new FileInputStream(keystorePath), keystorePassword);

            // Create and configure the SSL context
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(keystore, keystorePassword);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), null, null);

            // Create an SSL server socket
            SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
            SSLServerSocket serverSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(12345);

            System.out.println("Server listening on port 12345...");

            // Wait for a client to connect
            SSLSocket clientSocket = (SSLSocket) serverSocket.accept();

            System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

            // Get input and output streams for secure communication
            BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true); // autoFlush

            // Read data from client and respond
            String clientMessage;
            while ((clientMessage = reader.readLine()) != null) {
                System.out.println("Received from client: " + clientMessage);
                writer.println("Server received: " + clientMessage);
            }

            // Close resources
            reader.close();
            writer.close();
            clientSocket.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

TcpSampleClient

import java.io.*;
import java.net.Socket;

public class TcpSampleClient {
    public static void main(String[] args) {
        try {
            // Create a socket to connect to the server
            Socket socket = new Socket("localhost", 12345);

            // Get input and output streams for the socket
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            // Create readers and writers for easier communication
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter writer = new PrintWriter(outputStream, true); // autoFlush

            // Send a message to the server
            String message = "Hello, server!";
            writer.println(message);

            // Read response from the server
            String serverResponse = reader.readLine();
            System.out.println("Server response: " + serverResponse);

            // Close resources
            reader.close();
            writer.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

TcpSampleServer

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpSampleServer {
    public static void main(String[] args) {
        extracted();
    }

    private static void extracted() {
        try {
            // Create a server socket
            ServerSocket serverSocket = new ServerSocket(12345);

            System.out.println("Server listening on port 12345...");

            // Wait for a client to connect
            Socket clientSocket = serverSocket.accept();

            System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

            // Get input and output streams for the socket
            InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream();

            // Create readers and writers for easier communication
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter writer = new PrintWriter(outputStream, true); // autoFlush

            // Read data from client and respond
            String clientMessage;
            while ((clientMessage = reader.readLine()) != null) {
                System.out.println("Received from client: " + clientMessage);
                writer.println("Server received: " + clientMessage);
            }

            // Close resources
            //reader.close();
            //writer.close();
            //clientSocket.close();
            //serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

UdpSampleClient

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpSampleClient {public static void main(String[] args) {
        try {
            DatagramSocket clientSocket = new DatagramSocket();

            String message = "Hello, server!";
            byte[] sendData = message.getBytes();

            InetAddress serverAddress = InetAddress.getByName("localhost");
            int serverPort = 12345;

            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);
            clientSocket.send(sendPacket);

            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);

            String serverResponse = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Server response: " + serverResponse);

            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

UdpSampleSever

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpSampleSever {
    public static void main(String[] args) {
        try {
            DatagramSocket serverSocket = new DatagramSocket(12345);

            System.out.println("Server listening on port 12345...");

            byte[] receiveData = new byte[1024];

            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);

                String clientMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("Received from client: " + clientMessage);

                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();
                String serverResponse = "Server received: " + clientMessage;
                byte[] sendData = serverResponse.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

资料

超详细的wireshark抓包使用教程
jks证书文件的生成步骤
如何使用wireshark抓取HTTPS数据包?
wireshark抓包分析HTTPS
Burp Suite的基本介绍及使用
渗透测试工具Burp Suite详解
vmware ctrl键粘滞的问题
wireshark过滤规则
Burp Suite HTTPS详解

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/966695.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ModaHub魔搭社区专访百度智能云李莅:以后所有的数据库它都会原生地支持用向量?

ModaHub魔搭社区:您是否认为,以后所有的数据库它都会原生地支持用向量? 李莅:传统数据库广义上也分好几类:一类是关系型的,一类是 NoSQL 类的,还有一类是分析型的数据库。我觉得关系型的这种数据…

创建10个线程并发执行(STL/Windows/Linux)

C并发编程入门 目录 STL 写法 #include <thread> #include <iostream> using namespace std;void thread_fun(int arg) {cout << "one STL thread " << arg << " !" << endl; }int main(void) {int thread_count 1…

JS踩坑: for let 和 for var的区别

最近踩了一个js的坑 踩坑代码 如下两段代码&#xff0c;看起来没什么区别&#xff0c;但是实际运行效果却不一样 for (let i 0; i < 10; i) {console.log("for:" i);setTimeout(() > {console.log("setTimeout:" i);}, 1000); }输出&#xff1…

个性化定制你的AI助手,AI指令提示词专家

『个性化定制你的AI助手』围观不如下场&#xff01;需要学习AI指令提升能力的&#xff0c;精准输出想要内容的&#xff0c;快来订阅 javastarboy『AI指令保姆级拆解』合集&#xff01; ▶️你是否尚未挖掘到 AI 的潜力&#xff1f; ▶️你是否经常遇到“答非所问”的“人工智障…

手撕二叉平衡树

今天给大家带来的是平衡树的代码实现&#xff0c;如下&#xff1a; #pragma once #include <iostream> #include <map> #include <set> #include <assert.h> #include <math.h> using namespace std; namespace cc {template<class K, clas…

重装系统全流程

重点&#xff1a; 下载镜像网址&#xff1a;下载 Windows 10 (microsoft.com) 不过不用下载&#xff0c;你的美均相U盘里面有下载好的Win10系统 重点注意&#xff0c;重启后拔优盘&#xff0c;安装时不要联网

sql:SQL优化知识点记录(九)

&#xff08;1&#xff09;小表驱动大表 对sql调优的分析&#xff1a; 排序优化&#xff1a; 数据库的连接方式&#xff0c;里面的数据尽量这样连接&#xff0c;尽量选择第一个方式&#xff0c;因为两个表的连接一共建立5次连接&#xff0c;第二个建立1000次连接&#xff0c;从…

谁该来负责拥塞控制

寻找一种 host 公平而非 packet 公平的方法&#xff0c;有趣的是&#xff0c;CSMA/CD 网络就体现了这种方法。 端到端拥塞控制算法(cca)准不准先不论&#xff0c;仅说让它们运行&#xff0c;被控制的流至少要持续 2 个 RTT&#xff0c;一条持续传输的流是多数 cca 的约束。持续…

12. 自动化项目实战

目录 1. 登录测试 2. 测试首页的帖子列表数不为0 3. 帖子详情页校验 4. 发布帖子 5. 退出登录 自动化项目实施的基本流程如下图所示&#xff1a; 手工测试用例、自动化测试用例。 1. 登录测试 校验登录后主页显示的用户名称和登录时输入的用户名是否相等。 public class…

牛客小白月赛77 D-小Why的密码锁 双哈希做法

这道题没卡自然溢出的哈希&#xff0c;但mod为1e9的哈希被卡了。 双哈希只需把单哈希做法中的lst和ans转换成 <PII&#xff0c; int>类型的即可。 #include<bits/stdc.h> #define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define endl \nusing nam…

使用Docker安装和部署kkFileView

&#x1f388;1 参考文档 kkFileView官方文档 &#x1f680;2 安装kkFileView 拉取Redis镜像。 docker pull keking/kkfileview启动docker容器。 docker run -it -d -p 8012:8012 keking/kkfileview --restart always解释&#xff1a; docker run redis # 从kkfileview镜像运行…

ArcGIS Pro实践技术应用、制图、空间分析、影像分析、三维建模、空间统计分析与建模、python融合

GIS是利用电子计算机及其外部设备&#xff0c;采集、存储、分析和描述整个或部分地球表面与空间信息系统。简单地讲&#xff0c;它是在一定的地域内&#xff0c;将地理空间信息和 一些与该地域地理信息相关的属性信息结合起来&#xff0c;达到对地理和属性信息的综合管理。GIS的…

c语言每日一练(13)

前言&#xff1a;每日一练系列&#xff0c;每一期都包含5道选择题&#xff0c;2道编程题&#xff0c;博主会尽可能详细地进行讲解&#xff0c;令初学者也能听的清晰。每日一练系列会持续更新&#xff0c;上学期间将看学业情况更新。 五道选择题&#xff1a; 1、程序运行的结果…

理解 std::thread::join

C多线程并发编程入门&#xff08;目录&#xff09; 本文用最简单易懂的实际案例&#xff0c;讲清楚了 join 的实际内涵&#xff0c;保证你过目不忘。 Hello join 示例 join 函数是我们接触C多线程 thread 遇到的第一个函数。 比如&#xff1a; int main() {thread t(f);t.…

苹果Mac系统如何优化流畅的运行?提高运行速度

Mac系统的稳定性和流畅性一直备受大家称赞&#xff0c;这也是大多数人选择Mac的原因&#xff0c;尽管如此&#xff0c;我们仍不时地对Mac进行优化、调整&#xff0c;以使其比以前更快、更流畅地运行。以下是小编分享给各位的Mac优化方法&#xff0c;记得保存哦~ 一、释放被过度…

linux深入理解多进程间通信(未完)

1.进程间通信 1.1 进程间通信目的 数据传输&#xff1a;一个进程需要将它的数据发送给另一个进程资源共享&#xff1a;多个进程之间共享同样的资源。通知事件&#xff1a;一个进程需要向另一个或一组进程发送消息&#xff0c;通知它&#xff08;它们&#xff09;发生了某种事件…

MySQL总复习

目录 登录 显示数据库 创建数据库 删除数据库 使用数据库 创建表 添加数据表数据 查询表 添加数据表多条数据 查询表中某数据 增insert 删delete 改update 查select ​ where like ​编辑 范围查找 order by 聚合函数 count max min sum avg g…

创建2个线程并执行(STL/Windows/Linux)

C并发编程入门 目录 STL 写法 #include <thread> #include <iostream> using namespace std;void thread_fun1(void) {cout << "one STL thread 1!" << endl; }void thread_fun2(void) {cout << "one STL thread 2!" <…

ip地址、LINUX、与虚拟机

子网掩码&#xff0c;是用来固定网络号的&#xff0c;例如255&#xff0c;255,255,0&#xff0c;表明前面三段必须为网络号&#xff0c;后面必须是主机号&#xff0c;那么怎么实现网络复用呢&#xff0c;例如使用c类地址&#xff0c;但是正常子网掩码是255&#xff0c;255,255,…

抽象轻松的C语言

#include <stdio.h> /* 预处理指令*/ /* 函数 */ int main() {int log 3.14;printf("hello word * %d\n easy", log);getchar();/* 获取键盘输入的字母&#xff0c;在这个程序中的作用是防止程序瞬间关闭 */return 0; } 上一篇说过&#xff0c;C程序是C语言的…