TCP for Java Socket Programming

1.1 ServerSocket class
Create a ServerSocket class and set up a listening service at the specified port of the computer running the statement, such as:
ServerSocket MyListener=new ServerSocket(600);
Here we specify a port of 600 to provide listening services. A computer can provide multiple services at the same time. These different services are differentiated by port numbers. Different services are provided on different port numbers. To listen for possible Client requests at any time, execute the following statements:
Socket LinkSocket=MyListener.accept();
This statement calls the accept() method of the ServerSocket object. The execution of this method will keep the Server-side program in a waiting state. The program will block until it catches a request from the Client-side and returns a Link-Socket Socket object for communicating with the Client. Thereafter, as long as the Server program reads and writes data to this Socket object, it can read and write data to Client at the far end. Close the ServerSocket object at the end of the listen:
Mylistener.close();
1.2 Socket class
When the Client program needs to get information and other services from the Server side, it should create a Socket object:
Socket MySocket=new Socket("ServerComputerName",600);
The constructor of the Socket class has two parameters. The first parameter is the host address of the Server computer to be connected to, and the second parameter is the port number of the service provided on the Server machine.
Once the Socket object is successfully established, a connection can be established between Client and Server, and data can be transferred between the two endpoints through this connection. GettOutputStream () and getInputStream() of the Socket class are used to obtain input/output streams for reading and writing data to the Socket respectively. Finally, the data read from the Server end is returned to the Server end.
When the communication between Server and Client ends ends, the close() method of the Socket class can be called to close the Socket and remove the connection.

Server Socket is generally only used to set the port number and monitor. What really communicates is the socket on the server side and the socket on the client side. After the accept of Server Socket, the initiative is transferred.

  1. Server-side Programming
    On the server side, an object of ServerSocket class is created by using ServerSocket(int port), the constructor of ServerSocket class. The port parameter transfers the port. This port is the port where the server listens for connection requests. If an error occurs at this time, the IOException exception object will be thrown. Otherwise, the ServerSocket object will be created and opened. Start preparing to receive connection requests.
    The service program starts by calling the accept() method of ServerSocket until the connection is established. After establishing the connection, accept() returns a recently created Socket object that binds the client's IP address or port number.
    2. Client Programming
    When the client program needs to communicate with the server program, it needs to create a Socket object in the client. The Socket class has constructors Socket(InetAddress addr, int port) and Socket(String host, int port), both of which create a socket-based stream socket for connecting server-side stream sockets. For the first InetAd-dress subclass object, the IP address of the server host is obtained through the addr parameter. For the second function, the host parameter package is assigned to the InetAddress object. If the IP address is not consistent with the host parameter, the UnknownHostException exception object will be thrown. Both functions obtain the port number of the server through the parameter port. Assuming that a connection has been established, the network API will bundle the client's IP address and any port number in the client's socket-based stream socket, otherwise both functions will throw an IOException object.
    If a Socket object is created, it can read and transmit information from the input stream through the get-InputStream() method from the service program, or send messages by calling the getOutputStream() method to get the output stream. After the read-write activity is completed, the client calls the close() method to close the stream and the stream socket.
    Attached below is my demo:

Server-side code:

package com.example.demo.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Server
 * @author yangjy
 */
public class TcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader reader = null;
        try {
            serverSocket = new ServerSocket(9999);
            System.out.println("tcp The server has been started...");
            socket = serverSocket.accept();
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true) {
                String line = reader.readLine();
                if ("exit".equals(line)) {
                    break;
                }
                byte[] data = line.getBytes();
                System.out.println("Received " + socket.getInetAddress() + "Data:" + new String(data, 0, data.length));
            }
            System.out.println("tcp The service has dropped out...");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

Client code:

package com.example.demo.socket;

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

/**
 * Client
 * @author yangjy
 */
public class TcpClient {
    public static void main(String[] args) {
        Socket socket = null;
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            socket = new Socket("192.168.10.27", 9999);
            System.out.println("tcp The client starts...");
            reader = new BufferedReader(new InputStreamReader(System.in));
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            while (true) {
               String line = reader.readLine();
               writer.write(line);
               writer.newLine();
               writer.flush();
               if ("exit".equals(line)) {
                  break;
               }
            }
            System.out.println("tcp The client quit...");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                   reader.close();
                }
                if (socket != null) {
                   socket.close();
                }
                if (writer != null) {
                   writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Tags: socket Java Programming network

Posted on Mon, 26 Aug 2019 20:08:22 -0700 by warstormer