java network programming

Network Communications

1.1 Overview

Two major issues in network communication:

  • How to accurately locate one or more hosts on the network
  • How to communicate when a host is found

1.2 Elements of network communication

Address of both parties:

  • IP (ip class)
  • Port number (udp and tcp classes)

For example, 192.168.16.124:5900

  • Rule: Protocol for network communication

Everything is object

1.3 IP

ip address: InerAddress

  • Uniquely locate a host on a network
  • 127.0.0.1: localhost
  • Classification of ip addresses
    • ipv4/ipv6
      • ipv4 127.0.0.1, consisting of 4 bytes. 0-25.5 billion; 3 billion in North America, 400 million in Asia, and used up in 2011;
      • ipv6 128 bits, 8 unsigned integers for example: 2001:0bb2:aaaa:1150:0000:0000:bc21:0213
    • Public (Internet) / Private (LAN)
      • ABCD Class Address
      • 192.168.xx.xx is intended for use within an organization
  • Domain name: Memory IP
    • IP: Many IPs are no longer available and expensive to buy
import java.net.InetAddress;
import java.net.UnknownHostException;

//Test IP
public class TestInetAddress {
    public static void main(String[] args) {
        try {
            //Query local address
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            System.out.println(inetAddress2);
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress3);

            //Query ip address of website
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress4);

            //common method
            //System.out.println(inetAddress4.getAddress());
            System.out.println(inetAddress4.getCanonicalHostName());//Specification name
            System.out.println(inetAddress4.getHostAddress());//ip
            System.out.println(inetAddress4.getHostName());//domain name


        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

1.4 Port

Ports represent the processes of a program on a computer;

  • Different processes have different port numbers! Used to differentiate software!
  • Provisioned 0-65535
  • TCP UDP:65535*2, port number can not conflict under a single protocol
  • Port Classification
    • Public ports 0~1023
      • HTTP:80
      • HTTPS:443
      • FTP:21
      • Telent: 23
    • Program registration ports: 1024~49151, assign users or programs
      • Tomcat: 8080
      • MySQL: 3306
      • Oracle: 1521
    • Dynamic, Private: 19452~65535
netstat -ano #View all ports
netstat -ano|findstr "5900" #View the specified port
tasklisk|findstr '8696' #View processes on specified ports
import java.net.InetSocketAddress;

public class TestInetSockerAddress {
    public static void main(String[] args) {
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress socketAddress2 = new InetSocketAddress("localhost", 8080);
        System.out.println(socketAddress);
        System.out.println(socketAddress2);

        System.out.println(socketAddress.getAddress());
        System.out.println(socketAddress.getHostName());//address
        System.out.println(socketAddress.getPort());//port
    }
}

1.5 Communication Protocol

Agreement: agreement, just like what we are talking about now is Mandarin

Network Communication Protocols: Rate, Transmit Bit Rate, Code Structure, Transport Control...Very Complex

Small things: layered!

TCP/IP protocol cluster: actually a set of protocols

Important:

  • TCP: User Transfer Protocol (Analogue Phone)
  • UDP: User Datagram Protocol (Similar SMS)

Famous agreements:

  • TCP: User Transfer Protocol
  • IP: Network Interconnect Protocol

TCP UDP comparison

TCP: Call

  • Connection Stable
  • Three handshakes, four waves
Require at least three times for a stable connection
A: What do you see?
B: Look at you!
A: Do a job

A: I am afraid that l have to go
B: Are you really going to leave?
B: Do you really want to go?
A: I really have to go!
(Essentially A Send out, B Accept; B Send out, A Receive)
  • Client, Server
  • Transfer complete, connection released, inefficient

UDP: Send text messages

  • Disconnected, unstable
  • Client, server: no clear boundaries
  • Send it to you whether you're ready or not (just like a missile launches, it doesn't inform the target)
  • DDOS: Flood attack! (Saturation Attack)

1.6 TCP

Client

  1. Connect Server Socket
  2. send message
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

//Client
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket=null;
        OutputStream os=null;
        try {
            //1. To know the address and port number of the server
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port=9999;
            //2. Create a socket connection
            socket = new Socket(serverIP, port);
            //3. Send message, IO stream
            os = socket.getOutputStream();
            os.write("Hello, welcome to my blog".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

The server

  1. Set up a service's port ServerSocket
  2. Waiting for user's connection accept
  3. receive messages
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//Server
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        try {
            //1. I have to have an address
            serverSocket = new ServerSocket(9999);
            //2. Wait for the customer to link in
            socket = serverSocket.accept();
            //3. Waiting for messages from clients
            is = socket.getInputStream();

            //Pipeline Flow
            baos=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

File Upload

Client

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

public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1. Create a socket connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        //2. Create an output stream
        OutputStream os=socket.getOutputStream();
        //3. Read Files
        FileInputStream fis = new FileInputStream(new File("Head portrait.jpeg"));
        //4. Write out the file
        byte[] buffer = new byte[1024];
        int len;
        while((len=fis.read())!=-1){
            os.write(buffer,0,len);
        }

        //Last added: notify the server that I'm finished
        socket.shutdownOutput();//Notify the server that I have finished transferring

        //Confirm that the server has received before disconnecting
        InputStream inputStream = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer2 = new byte[2014];
        int len2;
        while((len=inputStream.read(buffer2))!=-1){
            baos.write(buffer2,0,len);
        }

        System.out.println(baos.toString());

        //5. Close resources
        baos.close();
        inputStream.close();
        fis.close();
        os.close();
        socket.close();
    }
}

The server

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

public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception {
        //1. Create a service
        ServerSocket serverSocket = new ServerSocket(9000);
        //2. Listen for client connections
        Socket socket = serverSocket.accept();
        //3. Get input stream
        InputStream is = socket.getInputStream();
        //4. File Output
        FileOutputStream fos = new FileOutputStream(new File("Receive.jpeg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len=is.read())!=-1){
            fos.write(buffer,0,len);
        }

        //Notify client that I have finished receiving
        OutputStream os = socket.getOutputStream();
        os.write("I'm done. You can disconnect".getBytes());


        //5. Close resources
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

Tomcat

Server

  • Custom S
  • Tomcat Server S: Java Background Development focuses on servers built with others!

Client

  • Custom C
  • Browser B

1.7 UDP

Text message: no connection, need to know each other's address

send message

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

//No need to connect to server
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1. Create a socket
        DatagramSocket socket = new DatagramSocket();

        //2. Build a package
        String msg="Hello, server!";

        //To whom
        InetAddress localhost = InetAddress.getByName("localhost");
        int port=9090;
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);

        //3. Send Packets
        socket.send(packet);

        //4. Close the stream
        socket.close();

    }
}

receiving end

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServerDemo01 {
    public static void main(String[] args) throws IOException {
        //Open Port
        DatagramSocket socket = new DatagramSocket(9090);

        //Receive Packets
        byte[] buffer=new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(packet);
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));

        //Close Connection
        socket.close();
    }
}

Send message circularly

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UdpSenderDemo02 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket();

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while(true){
            String data=reader.readLine();
            byte[] datas=data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas, 0, data.length(), new InetSocketAddress("localhost", 6666));
            socket.send(packet);

            if(data.equals("bye")){
                break;
            }
        }


        socket.close();
    }
}

Receive messages in a loop

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpReceiveDemo02 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        while(true){
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet);

            byte[] data = packet.getData();
            String receiveData= new String(data,0,data.length);
            System.out.println(receiveData);
            if(receiveData.equals("bye")){
                break;
            }

        }

        socket.close();
    }
}

Online Consulting

There are four parts: receiving, sending, teacher, student, two people can be either sender or receiver

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TalkSend implements Runnable{
    DatagramSocket socket =null;
    BufferedReader reader =null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try{
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while(true){
            try{
                String data=reader.readLine();
                byte[] datas=data.getBytes();
                DatagramPacket packet1 = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP,this.toPort));

                socket.send(packet1);

                if(data.equals("bye")){
                    break;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class TalkReceive implements Runnable {
    DatagramSocket socket = null;

    private int port;
    private String msgFrom ;

    public TalkReceive(int port, String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {

        while (true) {
            try {
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);

                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);

                System.out.println(msgFrom + ":" + receiveData);

                if (receiveData.equals("bye")) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
public class TalkStudent {
    public static void main(String[] args) {
        //Open two threads
        new Thread(new TalkSend(5555,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"Teacher")).start();
    }
}
public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(3333,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"Student")).start();
    }
}

1.8 URL

https://www.baidu.com/

Uniform Resource Locator: Locating a resource or a resource on the Internet

Protocol: // ip address: port/project name/resource

Tags: Java Network Communications

Posted by ugh82 on Tue, 05 Apr 2022 20:20:50 +0300