Java--Socket Programming TCP communication

Keywords: Programming socket Java network

Java--Socket Programming TCP communication

Blog description

The information involved in this article comes from Internet collation and personal summary, which means personal learning and experience summary. If there is any infringement, please contact me to delete, thank you!

Explain

TCP communication can realize data interaction between two computers. The two ends of communication should be strictly divided into Client and Server.

Steps for communication between two ends:

  1. The server program needs to be started in advance and wait for the connection of the client.
  2. The client actively connects to the server, and communication can only be achieved after the connection is successful. The server cannot actively connect to the client.

In Java, two classes are provided to implement the TCP communication program:

  1. Client: java.net.Socket class representation. Create a Socket object, send a connection request to the server, the server responds to the request, and the two establish a connection to start communication.
  2. Server: java.net.ServerSocket class representation. Creating a ServerSocket object is equivalent to opening a service and waiting for the client to connect.

Socket class

Socket class: this class implements client socket, which refers to the communication endpoint between two devices.

Construction method
  • public Socket(String host, int port): creates a socket object and connects it to the specified port number on the specified host. If the specified host is null, it is equivalent to specifying the address as the return address.
Socket client = new Socket("127.0.0.1", 8888);
Member method
  • public InputStream getInputStream(): returns the input stream for this socket.
    • If this ticket has an associated channel, all operations of the generated InputStream are also associated with that channel.
    • Closing the generated InputStream will also close the associated Socket.
  • public OutputStream getOutputStream(): returns the output stream of this socket.
    • If this ticket has an associated channel, all operations of the generated OutputStream are also associated with that channel.
    • Closing the generated OutputStream will also close the associated Socket.
  • public void close(): close this socket.
    • Once a socket is closed, it is no longer available.
    • Closing this socket will also close the related InputStream and OutputStream.
  • public void shutdownOutput(): disables the output stream for this socket.
    • Any previously written data will be sent and the output stream will be terminated.

ServerSocket class

ServerSocket class: this class implements the server socket, which is waiting for requests through the network.

Construction method
  • public ServerSocket(int port): when using this construction method to create a ServerSocket object, you can bind it to a specified port number. The parameter port is the port number.

For example, the code is as follows:

ServerSocket server = new ServerSocket(8888);
Member method
  • public Socket accept(): listen and accept the connection, and return a new Socket object for communication with the client. This method blocks until a connection is established.

TCP programming code implementation

thinking
  1. Start [server], create ServerSocket object and wait for connection.

  2. Start [Client], create Socket object and request connection.

  3. [server] receives the connection, calls the accept method, and returns a Socket object.

  4. [Client] Socket object, get OutputStream and write data to the server.

  5. [server end] the score object, which obtains the InputStream and reads the data sent by the client.

  6. [server] the Socket object, which obtains the OutputStream and writes back the data to the client.

  7. [Client] score object, get InputStream, parse and write back data.

  8. [Client] release resources and disconnect.

Code

Server

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author ServerTCP
 * @date 2020/4/25 10:51 morning
 */
public class ServerTCP {
    public static void main(String[] args) throws IOException {
        System.out.println("Service started, waiting for connection");
        //Create ServerSocket object, bind port, start waiting for connection
        ServerSocket ss = new ServerSocket(8888);
        //accept method, return socket object
        Socket server = ss.accept();
        //Get input object
        InputStream is = server.getInputStream();

        //Create byte array
        byte[] b = new byte[1024];
        //Read character array
        int len = is.read(b);
        //Parse character array
        String msg = new String(b,0,len);
        System.out.println(msg);

        //close resource
        is.close();
        server.close();
    }
}

client
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author ClientTCP
 * @date 2020/4/25 10:58 morning
 */
public class ClientTCP {
    public static void main(String[] args) throws IOException {
        System.out.println("Client sends data");
        //Create Socket
        Socket client = new Socket("127.0.0.1",8888);
        //Output stream
        OutputStream os = client.getOutputStream();
        //Write data
        os.write("Connect to server".getBytes());
        //close resource
        os.close();
        client.close();
    }
}

Result

TCP programming code implementation (mutual response)

Server

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author ServerTCP
 * @date 2020/4/25 10:51 morning
 */
public class ServerTCP {
    public static void main(String[] args) throws IOException {
        System.out.println("Service started, waiting for connection");
        //Create ServerSocket object, bind port, start waiting for connection
        ServerSocket ss = new ServerSocket(8888);
        //accept method, return socket object
        Socket server = ss.accept();
        //Get input object
        InputStream is = server.getInputStream();

        //Create byte array
        byte[] b = new byte[1024];
        //Read character array
        int len = is.read(b);
        //Parse character array
        String msg = new String(b,0,len);
        System.out.println(msg);

        //Respond
        OutputStream out = server.getOutputStream();
        out.write("I have received".getBytes());

        //close resource
        out.close();
        is.close();
        server.close();
    }
}

client

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author ClientTCP
 * @date 2020/4/25 10:58 morning
 */
public class ClientTCP {
    public static void main(String[] args) throws IOException {
        System.out.println("Client sends data");
        //Create Socket
        Socket client = new Socket("127.0.0.1",8888);
        //Output stream
        OutputStream os = client.getOutputStream();
        //Write data
        os.write("Connect to server".getBytes());

        InputStream in = client.getInputStream();
        byte[] b = new byte[1024];
        int len = in.read(b);
        System.out.println(new String(b,0,len));

        //close resource
        in.close();
        os.close();
        client.close();
    }
}

Result

The client has received a response from the server

Thank

Black horse programmer

And the industrious self

Posted by jiggens on Fri, 24 Apr 2020 21:06:00 -0700