SoFunction
Updated on 2025-04-04

Java uses TCP protocol to send and receive data

Java uses TCP protocol to send and receive data

1. TCP

TCP is a reliable connection-oriented transmission protocol

2. Java uses TCP to send data code

Three steps:

  • (1) Create the Socket object of the client
  • (2) Get the output stream and write data
  • (3) Release resources
import ;
import ;
import ;
import ;


public class TCPTest01 {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket(("uos-pc"), 10086);

        OutputStream os = ();
        ("FTP".getBytes());

        ();

    }
}

3. Java uses TCP to receive data code

Four steps:

  • (1) Create a server Socket object ServerSocket
  • (2) Listen to the client link and return the Socket object
  • (3) Get input stream, read data, and display on the console
  • (4) Release resources
import ;
import ;
import ;
import ;

public class TCPTest02 {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10086);
        Socket s = ();
        InputStream is = ();
        byte[] b = new byte[1024];
        int len = (b);
        String data = new String(b, 0, len);
        (data);
        ();
        ();
    }
}

4. Execute

Start and

You can see the output TCP in the console

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.