Java Socket Communication Based on TCP/IP

Socket communication based on TCP/IP transmits data through input stream and output stream. Before that, the connection between the server and the client must be realized. After the client and the server shake hands three times to confirm the connection, they can communicate through the corresponding stream. The three-way handshake confirmation of TCP/IP Socket communication makes the communication relatively safe and reliable.

The Socket client is implemented by the ServerSocket class

Some methods of the ServerSocket class:

Construction method
ServerSocket(int port)
Creates a server socket, bound to the specified port.
Create a socket service and bind it to a specific port.

Note:

The port numbers are 0~65535, among which 0~1023 are reserved ports for the system, so you can choose any port within 1024~65535.

Socket accept() throws IOException
Listens for a connection to be made to this socket and accepts it.
Listen for and accept socket connections.

Note:

The method returns a Socket object connected by the client, through which the input stream and output stream can be obtained to communicate with the client;

When a thread calls the accept() method without a socket connection, the thread will be blocked;

If you call setSoTimeOut(int timeout) to set the waiting time before calling the accept() method, and there is no socket connection after the waiting time, the method will throw a SocketTimeoutException (the parameter of setSoTimeOut(int) is milliseconds).

void close()
Closes this socket.
close the socket

InetAddress getInetAddress()
Returns the local address of this server socket.
Returns the address of the local socket service (InetAddress object)

boolean isBound()
Returns the binding state of the ServerSocket.
boolean isClosed()
Returns the closed state of the ServerSocket.

The Socket client connects to the server by creating a Socket class object

Some methods of the Socket class:

Construction method
Socket(InetAddress address, int port)
Socket(String host, int port)
Creates a stream socket and connects it to the specified port number at the specified IP address.
Create a streaming socket and connect to a specific port at a specific IP address

Note:

The InetAddress object in the previous construction method can be obtained by several static methods of the InetAddress class;

In the latter construction method, String host can be a host name or an IP address.

void close()
Close this socket.

InetAddress getInetAddress()
Returns the address to which the socket is connected.
Returns the address the socket is connected to (InetAddress object)

InputStream getInputStream()
OutputStream getOutputStream()
Get input stream and output stream

void shutdownInput()
void shutdownOutput()
close input and output streams

The content quoted above is from Java API 1.8.0
More related classes and methods can be found in Java API

Server implementation
  1. Create a ServerSocket instance and start the server
  2. Waiting for client connection
  3. Get input stream output stream for communication
  4. Close related resources
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public void start() throws IOException {//throw the exception

        //Create a ServerSocket instance, bind port 8000, and start the service
        ServerSocket server = new ServerSocket(8000);
        InetAddress address = InetAddress.getLocalHost();
        System.out.println(address + "server start");

        //Waiting for a client to connect, the thread blocks until a client connects
        Socket socket = server.accept();

        //get output stream
        InputStream input = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line;
        while((line = reader.readLine()) != null){
            System.out.println(line);
        }

        //close resource
        socket.shutdownInput();
        reader.close();
        socket.close();

        //close service
        server.close();
    }   

    public static void main(String[] args) {
        try {
            new Server().start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
client implementation
  1. Create a Socket instance and connect to the specified server
  2. Get input stream and output stream to communicate
  3. Close related resources
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

    public void start() throws IOException {//throw the exception

        //Create a Socket instance and connect to port 8000 of localhost
        Socket socket = new Socket("localhost", 8000);

        //get output stream
        OutputStream output = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(output);
        writer.write("client connection");
        writer.flush();

        //close resource
        socket.shutdownOutput();
        writer.close();
        socket.close();

    }

    public static void main(String[] arg){
        try {
            new Client().start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Tags: Java socket

Posted by abhishek on Mon, 09 Jan 2023 13:47:41 +0530