Network programming

Basic concepts of network programming 2 IP address and port number 3 Communication protocol 4 TCP communication code practice 4.1 Message transfer 4.2 File upload 5 UDP communication code 5.1 UDP message sending 5.2 Using UDP to send and receive messages 5.3 Using UDP to chatCopy the code

1. Basic concepts of network programming

quotes

Before we look at network programming, let’s look at an example. Generally in our classmate in this age group, has experienced the experience of writing/post the letter, at the time of writing, we usually need to clear the area where address, contact information and send the zip code, the postman can find receiving letters according to the information on this, recipient after reading the content of the letter can be in the same way to reply, This allows friends in distant places to communicate with each other.

In this case, distant friends must meet the following conditions if they wish to communicate

1. Location and detailed address of the recipient

2. There needs to be a Courier to receive and send

Gradually, with the development of science and technology, we have mobile phone communication, QQ chat, wechat chat and other communication methods, using these methods we can communicate more convenient, but no matter which way, the communication process always need such two elements: address and transmission process.

In network communication, these two elements can be replaced with more technical nouns:

1. IP address and port number

The IP address can help us find the receiver of the communication, and the port number can help us find the specific application in the computer, such as QQ and wechat

2. Transmission protocol

Protocols are used for better transmission, such as TCP, UDP, FTP, SMTP, and HTTP

2. IP address and port number

An IP address is an Internet protocol address, which is a unified address format. Every host on the Internet has a logical address. In computer networks, localhost (which stands for “this computer”) is a standard host name returned with an IP address of 127.0.0.1

With the IP address, we can connect to the specified computer, but we also need to know the port number if we want to access an application on the target computer. In computing, different applications are distinguished by port numbers.

In network programming, InetAddress can be used for host name resolution and reverse resolution, that is, given a certain host name, return a certain IP address; Given an IP address, return the host name

Localhost resolves to 127.0.0.1

127.0.0.1 Reversely resolves to localhost

NOTE: Ports for different protocols can be repeated, such as UDP and TCP

Port query operations

Netstat netstat - ano ano # to check all the port | findstr searches "XXX" # check the specified portCopy the code

3. Communication protocol

IP address and port number to solve the problem the address in the process of communication, but in a computer, we need to solve the problem of how to communication, the communication is how to communicate between computers, and communication protocol is the computer on both sides to follow one of the rules and conventions (like mandarin, English), it can be through the communication channel will be in different location of devices connected, It can realize information exchange and resource sharing.

In the computer network, the commonly used protocol is TCP/IP, it is a protocol cluster, composed of multiple sub-protocols, such as our common TCP, IP, UDP, ARP and so on, we mainly explain the network programming commonly used TCP, UDP and IP

  • TCP

TCP is a connection-oriented, reliable, byte stream – based transport layer communication protocol

  • UDP

UDP is a connectionless transport protocol that sends data packets without establishing a connection

  • IP

IP Protocol The core of the entire TCP/IP protocol family, which can carry the information of various protocols at the transport layer, such as TCP and UDP. IP packets can be placed in the link layer and transmitted through Ethernet and other technologies.

Comparison between TCP and UDP

TCP can be analogous to a phone call with the following characteristics

  • Before data can be transferred, a connection needs to be established (Three-way handshake), so the connection is stable and reliable
  • There is the concept of client, server, client sending, server receiving
  • When the transfer is complete, the connection is released (Four times to wave)

UDP can be likened to SMS with the following characteristics

  • Before data transmission, there is no need to establish a connection, so it is not reliable and unstable
  • There is no clear distinction between client and server. Both client and server can send/receive messages
  • There is no need to establish a connection, so it is faster

4. TCP communication code practice

TCP network programming requires the following Java classes

InetAddress: indicates the IP address. The IP address and host name can be resolved

Socket: To implement the client Socket, establish a connection, Socket is the communication between two machines endpoint

ServerSocket: implements the ServerSocket

4.1 Message Passing

The client

1. Obtain the IP address and port number of the server (InetAddress)

2. Establish a Socket connection

3. Send the MESSAGE

public class TcpClient {
    public static void main(String[] args) throws IOException {
        Socket socket=null;
        OutputStream os=null;
        try {
            // get the server address and port number
            InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
            int port=9898;
            //2. Establish a Socket connection
          socket=new Socket(inetAddress,port);
            //3
            os=socket.getOutputStream();
            os.write("hello,Simon".getBytes());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // Close the resourceos.close(); socket.close(); }}}Copy the code

The service side

1. Set your own port number using ServerSocket

2. Waiting for the connection, Socket

2.1: You can wait for a connection and close it after receiving a message

2.2: Wait for multiple connections. Wrap the method of waiting for connections with while(true) and receive messages repeatedly

3. Obtain the message from the sender

public class TcpServer {
    public static void  main(String[] args) throws IOException {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        try {
            //1. Set your own port number
            serverSocket=new ServerSocket(9898);
            //2. Wait for the client to connect
            socket=serverSocket.accept();
            //3. Read the client message
            is=socket.getInputStream();
            baos=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len;
            while((len=is.read(buffer))! = -1){
                baos.write(buffer,0,len);
            }
            System.out.print(baos.toString());

        }catch (Exception e){
            e.printStackTrace();
        }finally{ baos.close(); is.close(); socket.close(); serverSocket.close(); }}}Copy the code

4.2 Uploading Files

The client

1. Create a connection

2. Create a byte output stream for communication

Create a file input stream to receive the file, and then feed the received file to the byte output stream for communication

3. After the output is complete, call the shutdownInput method to notify the server that the output is complete

4. Close the connection resource

public class TcpFileClient {
    public static void main(String[] args) throws Exception {

        // create a connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9987);
        //2. Define an output stream for communication
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("simon.png"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) ! = -1) {
            os.write(buffer, 0, len);
        }
        //3. Notify the server that I am finished
        socket.shutdownOutput();

        // Make sure that the server receives the end message before disconnecting
       InputStream inputStream= socket.getInputStream();
        byte[] buffer2=new byte[1024];
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        int len2;
        while((len2=inputStream.read(buffer2))! = -1){
            baos.write(buffer2,0,len2);
        }
        System.out.print(baos.toString());
        // Close the connectionbaos.close(); inputStream.close(); os.close(); fis.close(); socket.close(); }}Copy the code

The service side

1. Create a connection and wait for the client to access

2. Create an input stream

Create a file output stream and output the input stream

3. Close the resource

public class TcpFileServerDemo02 {
    public static void main(String[] args) throws Exception {
        // Set the port number
        ServerSocket serverSocket=new ServerSocket(9987);
        // Wait for connection
        Socket socket=serverSocket.accept();
        // Get the input stream
        InputStream is=socket.getInputStream();
        // File output
        FileOutputStream fos=new FileOutputStream(new File("snow.png"));
        byte[] buffer=new byte[1024];
        int len;
        while((len=is.read(buffer))! = -1){
            fos.write(buffer,0,len);
        }
        // Notify client that receiving is complete
        OutputStream os=socket.getOutputStream();
        os.write("I have received the end, you can disconnect.".getBytes());

        // Close the resourcefos.close(); is.close(); socket.close(); serverSocket.close(); }}Copy the code

5. UDP communication code

UDP does not need to connect, but needs to know the address and port number of the other party, mainly using the following Java class

DatagramPacket: Indicates the data packet used to implement the connectionless packet transmission service

DatagramSocket: Represents the socket used to send and receive datagrams

UDP does not have client and server concepts, but for programming simulation convenience, we assume that there are clients and servers

5.1 UDP Message Sending

The client

  • Establish a connection
  • Creating a packet
  • Send packet
public class UdpClientDemo1 {
    public static void main(String[] args) throws Exception {
        // set up a connection (this port number is client)
        DatagramSocket datagramSocket=new DatagramSocket(9888);
        //2
        String msg="hello,Simon";
        InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
        // Data, starting position of data, address to send and port number
        DatagramPacket datagramPacket=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,inetAddress,9887);
        //3. Send the packet
        datagramSocket.send(datagramPacket);
        // Close the data streamdatagramSocket.close(); }}Copy the code

The service side

  • Establish a connection
  • Receive data
public class UdpServerDemo2 {
    public static void main(String[] args) throws Exception{
        // Establish a connection, open the port
        DatagramSocket datagramSocket=new DatagramSocket(9887);
        // Receive packets
        byte[] buffer=new byte[1024];
        DatagramPacket datagramPacket=new DatagramPacket(buffer,0,buffer.length);
        datagramSocket.receive(datagramPacket);
        // Prints packet information
        System.out.println(datagramPacket.getAddress());
        System.out.println(datagramPacket.getPort());
        System.out.println(new String(datagramPacket.getData()));
        // Close the connection
        datagramSocket.close();
    }
Copy the code

5.2 Using UDP to Send and Receive Messages

Use the while(true) method to wrap the sending and receiving data on the client side, as long as they meet certain conditions (such as the input string “bye”) and exit. This allows you to send and receive messages in a loop.

The client

public class UdpSend {
    public static void main(String[] args) throws Exception {
        // Create a connection
        DatagramSocket datagramSocket=new DatagramSocket(9888);
        //2, create a packet from the keyboard input
        InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
        int port=9887;
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        while (true){
            String s=bufferedReader.readLine();
            DatagramPacket datagramPacket=new DatagramPacket(s.getBytes(),0,s.getBytes().length,inetAddress,9887);
            //3. Send data
            datagramSocket.send(datagramPacket);
            if(s.equals("bye")) {break; }}// Close datadatagramSocket.close(); }}Copy the code

The service side

public class UdpReceive{
    public static void main(String[] args) throws Exception {
        // Create a connection
        DatagramSocket datagramSocket=new DatagramSocket(9887);
        while (true) {//2
           byte[] buffer=new byte[1024];
            DatagramPacket datagramPacket=new DatagramPacket(buffer,0,buffer.length);
            datagramSocket.receive(datagramPacket);
            //3. Disconnect
            byte[] data=datagramPacket.getData();
            String receiveData=new String(data,0,data.length);
            System.out.println(receiveData);
            if(receiveData.equals("bye")) {break; } } datagramSocket.close(); }}Copy the code

5.3 Using UDP for Chat

With UDP chat, the client and server (there is no such thing as client and server) need to receive and send messages, which requires multithreading support.

We first construct two receiving and sending thread classes, and then two user classes to communicate.

Send the class

public class TalkSend implements Runnable {
    DatagramSocket datagramSocket = null;
    BufferedReader bufferedReader = null;

    private int fromPort;
    private int toPort;
    private String toIp;

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

        // Create a connection
        try {
            datagramSocket = new DatagramSocket(fromPort);
            //2, create a packet from the keyboard input
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        } catch(SocketException e) { e.printStackTrace(); }}@Override
    public void run(a) {
        while (true) {
            try {
                String s = bufferedReader.readLine();
                DatagramPacket datagramPacket = new DatagramPacket(s.getBytes(), 0, s.getBytes().length, new InetSocketAddress(toIp,toPort));
                //3. Send data
                datagramSocket.send(datagramPacket);
                if (s.equals("bye")) {
                    break; }}catch(IOException e) { e.printStackTrace(); }}// Close datadatagramSocket.close(); }}Copy the code

Receive class

public class TalkReceive implements Runnable{
    DatagramSocket datagramSocket=null;
    private int port;
    private String msgFrom;

    public TalkReceive(int port,String msgFrom)  {
        this.port=port;
        this.msgFrom=msgFrom;

        // Create a connection
        try {
            datagramSocket=new DatagramSocket(port);
        } catch(Exception e) { e.printStackTrace(); }}@Override
    public void run(a) {
        while (true) {try {
                //2
                byte[] buffer=new byte[1024];
                DatagramPacket datagramPacket=new DatagramPacket(buffer,0,buffer.length);
                datagramSocket.receive(datagramPacket);
                //3. Disconnect
                byte[] data=datagramPacket.getData();
                String receiveData=new String(data,0,data.length);
                System.out.println(msgFrom+":"+receiveData);
                if(receiveData.equals("bye")) {break; }}catch(Exception e) { e.printStackTrace(); } } datagramSocket.close(); }}Copy the code

The user class 1

public class TalkStudent {
    public static void main(String[] args) {
        new Thread(new TalkSend(7777.9999."localhost")).start();
        new Thread(new TalkReceive(8888."Small")).start(); }}Copy the code

The user class 2

public class TalkTeacher {
    public static void main(String[] args){
        new Thread(new TalkSend(5555.8888."localhost")).start();
        new Thread(new TalkReceive(9999."Little lang")).start(); }}Copy the code