Java foundation - network programming

Posted by furma on Mon, 14 Feb 2022 03:02:36 +0100

  • B/S and C/S architecture

B/S: Browser / server, which interacts with the server based on the browser program
C/S: client / server, which interacts with the server based on the client program

  • Java write server program

1. Meet business needs
2. Handle high concurrency
3. Big data processing

  • Network protocol

Syntax: structure of data
Semantics: describe request and response
Synchronization: implementation sequence of actions

  • TCP/IP protocol

application layer
Transport layer
Internet layer
Network interface layer

  • Common methods of InetAddress
methoddescribe
public InetAddress getLocalHost()Gets the InetAddress object of the local machine
public InetAddress getByName(String host)Create InetAddress object by hostname
public String getHostName()Get host name
public String getHostAddress()Get host IP address
public InetAddress getByAddress(byte[] addr)Create InetAddress object from IP address
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println(inetAddress);
        System.out.println(inetAddress.getHostName());
        System.out.println(inetAddress.getHostAddress());

        InetAddress inetAddress1 = inetAddress.getByName("localhost");
        System.out.println(inetAddress1);
  • URL common methods
methoddescribe
public URL(String IP,String host,int port,String file)Obtain the URL object according to the protocol, IP address, port number and resource name
public InputStream openStream()Get input stream object
 public static void main(String[] args) {
        InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL("http","127.0.0.1",8080,"/login.html");
            inputStream = url.openStream();
            reader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(reader);
            String str = null;
            while ((str = bufferedReader.readLine())!=null){
                System.out.println(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                reader.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • TCP protocol

Java completes the development of TCP programs through socket. Socket is a class that can be used to establish a reliable connection between the server and the client. In the actual development, the socket represents the client and the server uses ServerSocket. ServerSocket is also a class, which is stored in Java Net package.
The server creates a ServerSocket object and receives several Socket objects representing the client through the accpet() method to realize data interaction.

  • Common methods of ServerSocket
methoddescribe
public ServerSocket(int port)Create ServerSocket object based on port
public ServerSocket(int port,InetAddress address)Create a ServerSocket object based on the port and InetAddress
public int getSoTimeout()Get SoTimeout
public InetAddress getInetAddress()Get server IP address
public Socket accpet()Waiting for client requests
  • Common Socket methods
methoddescribe
public Socket(String host,int port)Create the Socket object to be connected according to the host and port
public Socket(InetAddress host,int port)Create the Socket object to be connected according to the IP address and port
public Socket()Create an unconnected Socket object
public InputStream getInputStream()Return the input stream of Socket
public void close()Close Socket
public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            serverSocket = new ServerSocket(8080);
            System.out.println("------Server------");
            System.out.println("Started, waiting to receive client requests...");
            boolean flag = true;
            while(flag){
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                dataInputStream = new DataInputStream(inputStream);
                String request = dataInputStream.readUTF();
                System.out.println("Client request received:" + request);
                String response = "Received your request, OK";
                System.out.println("Respond to clients:" + response);
                outputStream = socket.getOutputStream();
                dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeUTF(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dataInputStream.close();
                inputStream.close();
                socket.close();
                serverSocket.close();
                dataOutputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;
        try {
            socket = new Socket("127.0.0.1", 8080);
            System.out.println("------client------");
            String request = "Hello";
            System.out.println("The client said:" + request);
            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(request);
            inputStream = socket.getInputStream();
            dataInputStream = new DataInputStream(inputStream);
            String response = dataInputStream.readUTF();
            System.out.println("The server response is:" + response);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dataOutputStream.close();
                outputStream.close();
                socket.close();
                dataInputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • Common methods of datagram socket
methoddescribe
public DatagramSocket(int port)create object
public void send(DatagramPacket p)Send packet
public void receive(DatagramPacket p)Receive packet
  • Common methods of datagram packet
methoddescribe
public DatagramPacket(byte buf[],int length,InetAddress address,int port)Create package
public byte[] getData()get data
public int getLength()Get data length
public int getPort()Get the port to send the packet
public SocketAddress getSocketAddress()Get the Socket information of sending data
public class TerminalA {
    public static void main(String[] args) {
        try {
            //receive data 
            byte[] buff = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(buff, buff.length);
            DatagramSocket datagramSocket = new DatagramSocket(8181);
            datagramSocket.receive(datagramPacket);
            String message = new String(datagramPacket.getData(),0,datagramPacket.getLength());
            System.out.println("I am TerminalA,Got it"
                    + datagramPacket.getSocketAddress().toString() +
                    ":" + datagramPacket.getPort() + "Data from:" + message);
            //send data
            String response = "I am TerminalA,The data you sent has been received.";
            SocketAddress socketAddress = datagramPacket.getSocketAddress();
            DatagramPacket datagramPacket2 = new DatagramPacket(
                    response.getBytes(),
                    response.getBytes().length,
                    socketAddress);
            datagramSocket.send(datagramPacket2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class TerminalB {
    public static void main(String[] args) {
        try {
            //send message
            String message = "I am TerminalB,Hello!";
            InetAddress inetAddress = InetAddress.getByName("localhost");
            DatagramPacket datagramPacket = new DatagramPacket(
                    message.getBytes(),
                    message.getBytes().length,
                    inetAddress,
                    8181);
            DatagramSocket datagramSocket = new DatagramSocket(8080);
            datagramSocket.send(datagramPacket);
            //receive messages
            byte[] buff = new byte[1024];
            DatagramPacket datagramPacket2 = new DatagramPacket(buff, buff.length);
            datagramSocket.receive(datagramPacket2);
            String response = new String(datagramPacket2.getData(),0,datagramPacket2.getLength());
            System.out.println("I am TerminalB,Got it" + datagramPacket2.getSocketAddress().toString() + ":" +
                    datagramPacket2.getPort() + "Returned data:" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • TCP under multithreading
public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8080);
            System.out.println("Server started");
            while (true){
                Socket socket = serverSocket.accept();
                new Thread(new ServerRunnable(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ServerRunnable implements Runnable {

    private Socket socket;

    public ServerRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;
        try {
            inputStream = this.socket.getInputStream();
            dataInputStream = new DataInputStream(inputStream);
            String request = dataInputStream.readUTF();
            System.out.println(request);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                dataInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Client {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(new ClientRunnable(i)).start();
        }
    }
}
public class ClientRunnable implements Runnable {
    private int num;
    public ClientRunnable(int num) {
        this.num = num;
    }
    @Override
    public void run() {
        Socket socket = null;
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            socket = new Socket("localhost", 8080);
            String message = "I'm a client"+this.num;
            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dataOutputStream.close();
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Topics: Java network server Network Protocol