java network programming (socket (Tcp small Dome))

Java stream

Before network programming, we must understand how important streaming is to Java. We can store and read files through streams, and also transmit network data through streams. There is no concept of pointer in Java. We know that in C language, it regards all abstract concepts such as screen and keyboard as files, corresponding to pointer (such as screen stdout standard output and stdin standard input). Then in Java, stream also acts as a pointer like job.

socket definition

What is socket? This thing is actually the open interface of our network driver. We use it to complete the connection data of our network. Of course, there are subtle differences in the specific operations in different computer languages. For example, in Java, we can directly use character stream for Chinese direct transmission, but in python, the data must be converted into bytes before decoding.
1, Java

2, python

    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    id = socket.gethostbyname(socket.gethostname()).split(":")[0]
    s.connect((id,8089))
    s.send('Hello!'.encode('utf8'))
    print("Data transmission completed")
    tes=s.recv(1024)
    print(tes.decode('utf8'))
    s.close()

Use of Java socket

Flowchart of socket
I The process of sending data

II Process of receiving data

Basic methods to be used for socket in Java

Here we need to know three methods first

  1. getInputStream() can get the data stream transmitted in the network (the data sent to the current device is directly obtained from the network card)

  2. getOutputStream() is a stream used to send the data you want to send

  3. accept() is used by the server to answer whether there is data incoming and whether there is a connection. The return type is socket

In addition, sockets are used on the client and servicesocket s are used on the server

Server code
Here, it is convenient to write two for reference. One is Java and the other is python
One java

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


public class EchoServiceDome {

public static void main(String[] args) {
    try {

        ServerSocket server = new ServerSocket(6666);
        System.out.println("The server has started and is waiting for a client connection");
        Socket socket = server.accept();//It is blocked when it is the same as python 
        System.out.println("Client connection succeeded:"+server.getInetAddress().getHostAddress());
        //socke.getInputStream() transfers data through the stream, so we can use this to get and accept
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //Read the data of that network
        String info = br.readLine();
        System.out.println(info);

        //Write data and return to the client
        PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
        ps.println("echo:"+info);
        ps.flush();
        ps.close();
        br.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

II. python

    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    id = socket.gethostbyname(socket.gethostname()).split(":")[0]
    s.connect((id,8089))
    s.send('hello'.encode('utf8'))
    print("Data transmission completed")
    tes=s.recv(1024)
    print(tes.decode('utf8'))
    s.close()

client

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class EchoClientDome {
    public static void main(String[] args) {
        
        //We transmit directly through the character stream, so we don't need to be the same as python. We decode it after it is converted to bytes
        //It is mainly useful that python has done a lot of encapsulation, which is essentially similar
        try {
            //Connect server
            Socket  socket = new Socket("localhost",6666);
            PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));//Send to server
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//Take over the feedback from the server

            ps.println("Hello");
            ps.flush();
            //Reading will be blocked before the server sends data, that is, it will wait for the server to respond.
            String info = br.readLine();
            System.out.println(info);
            ps.close();
            br.close();

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

II. python

    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    id = socket.gethostbyname(socket.gethostname()).split(":")[0]
    s.bind((id,8089))
    print("TCP Server on")
    s.listen(128)
    data,ip_where=s.accept()
    print(data.recv(1024).decode('utf8'))
    data.send('world'.encode('utf8'))

Keywords: Python Java network socket

Added by iii on Sun, 16 Jan 2022 14:07:33 +0200