Use Socket in java to complete TCP protocol or UDP protocol communication

Keywords: Java network udp TCP/IP

Use Socket in java to complete TCP protocol or UDP protocol communication

Introduce TCP and UDP

Two types of transmission protocols: TCP; UDP

TCP is the abbreviation of Tranfer Control Protocol. It is a connection oriented protocol to ensure reliable transmission. Through TCP protocol transmission, we get a sequential error free data stream. A connection must be established between the two paired sockets of the sender and the receiver in order to communicate on the basis of TCP protocol. When one socket (usually server socket) waits to establish a connection, the other socket can request a connection. Once the two sockets are connected, they can carry out two-way data transmission, Both parties can send or receive.

UDP is the abbreviation of User Datagram Protocol. It is a connectionless protocol. Each datagram is an independent information, including a complete source address or destination address. It is transmitted to the destination by any possible path on the network. Therefore, whether it can reach the destination, the time to reach the destination and the correctness of the content cannot be guaranteed.

Comparison:

UDP:

1. Complete address information is given in each datagram, so there is no need to establish a connection between the sender and the receiver.

2. There is a size limit when UDP transmits data. Each transmitted packet must be limited to 64KB.

3. UDP is an unreliable protocol. The datagrams sent by the sender do not necessarily arrive at the receiver in the same order

TCP:

1. For connection oriented protocol, a connection must be established before data transmission between socket s, so connection time is required in TCP.
2. The size of TCP transmission data is limited. Once the connection is established, the socket s of both sides can transmit large data in a unified format.
3. TCP is a reliable protocol, which ensures that the receiver completely and correctly obtains all the data sent by the sender.

Application:

1. TCP has strong vitality in network communication. For example, both remote connection (Telnet) and file transfer (FTP) require variable length data to be reliably transmitted. However, reliable transmission has to pay a price. The verification of the correctness of data content will inevitably occupy the processing time of the computer and the bandwidth of the network. Therefore, the efficiency of TCP transmission is not as high as UDP.

2. UDP is easy to operate and requires less monitoring. Therefore, it is usually used for client/server applications in decentralized systems with high reliability of LAN. For example, the video conference system does not require the audio and video data to be absolutely correct, as long as the consistency is guaranteed. In this case, it is obviously more reasonable to use UDP.

3, java network programming based on Socket

1. What is Socket

Two programs on the network exchange data through a two-way communication connection. One end of the two-way link is called a socket. Socket is usually used to connect the client and the server. Socket is a very popular programming interface of TCP/IP protocol. A socket is uniquely determined by an IP address and a port number.

However, TCP/IP is not the only protocol supported by Socket, so there is no inevitable relationship between them. In the Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol.

2. Socket communication process

The Server side listens to whether a port has a connection request. The Client side sends a connect request to the Server side, and the Server side sends an Accept message back to the Client side. A connection is established. Both Server and Client can communicate with each other through Send, Write and other methods.

A fully functional Socket must contain the following basic structure, and its working process includes the following four basic steps:

(1) Create a Socket;

(2) Open the input / output stream connected to the Socket;

(3) Read / write the Socket according to a certain protocol;

(4) Close Socket

Socket communication of TCP protocol

client

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//Customer service end
public class TCPClient {
    public static void main(String[] args) throws IOException {

        //Create and server connections
        Socket socket =new Socket("127.0.0.1",8888);
		
        //Send the client message to the server
        OutputStream os = socket.getOutputStream();
        os.write("Hello server".getBytes());
		//Accept the message returned by the server
        InputStream is=socket.getInputStream();
        byte[] bytes=new byte[1024];
        int len=is.read(bytes);
        System.out.println(new String(bytes,0,len));
		//Turn off socket communication
        socket.close();

    }
    
}

Server

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {


    public static void main(String[] args) throws IOException {
			//Specify the port to access the customer service terminal
        ServerSocket server=new ServerSocket(8888);
		// Receive data sent by the client. If not received, it will be blocked consistently
        Socket socket=server.accept();
		// Read requested information
        InputStream is=socket.getInputStream();
        byte[] bytes=new byte[1024];
        int len=is.read(bytes);
        System.out.println(new String(bytes,0,len));

		// The server returns a message to the client 
        OutputStream os= socket.getOutputStream();
        os.write("Yes, thank you".getBytes());
        socket.close();
        server.close();



    }
}

Start the server first, and then start the customer service. Otherwise, an error will be reported that the connection failed because the server was not found

The final effect is:

The server receives the information from the customer service. Hello to the server

The client receives the message returned by the server. Thank you

Socket communication of UDP protocol

Customer service end

package UDP;

import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class SocketClient {

    public static void main(String[] args) {
        try {
            // The message to be sent by the client to the server
            String sendMsg = "Messages sent by clients";
            //Length of occurrence
            int  sendMsgLength=sendMsg.getBytes().length;
            // Get the address of the server
            InetAddress addr = InetAddress.getByName("localhost");

            // Create a packet object to encapsulate the packet data to be sent and the server address and port number
            DatagramPacket packet = new DatagramPacket(sendMsg.getBytes(),sendMsgLength , addr, 8088);

            // Create Socket object
            DatagramSocket socket = new DatagramSocket();
            // Send message to server
            socket.send(packet);

            //Receive data from the server
            byte[] receBuf = new byte[1024];
            DatagramPacket recePacket = new DatagramPacket(receBuf, receBuf.length);
            socket .receive(recePacket);
            String receStr = new String(recePacket.getData(), 0 , recePacket.getLength());
            System.out.println( receStr);


            // Close socket
            socket.close();

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

Server

package UDP;

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

public class SocketServer {

    public static void main(String[] args) {
        try {
            // Message to be received
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);

            // Create socket and specify port
            DatagramSocket socket = new DatagramSocket(8088);

            // Receive data sent by the client. If not received, it will be blocked consistently
            socket.receive(packet);
            String receiveMsg = new String(packet.getData(),0,packet.getLength());
            System.out.println(receiveMsg);


            // The message to be sent by the service to the client
            String sendMsg = "Messages sent by the server";
            //Length of occurrence
            packet.setData(sendMsg.getBytes());
            packet.setLength(sendMsg.getBytes().length);
            // Create a packet object to encapsulate the packet data to be sent and the server address and port number
            // Send message to server
            socket.send(packet);


            // Close socket
            socket.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }


}

Start the server first, and then start the customer service terminal, otherwise the customer service terminal will fall into wireless waiting

The final effect is:

The server receives the information from the customer service and the message from the client

The client receives the message returned by the server and the message sent by the server

Implementation of socket long connection server

The previous Client/Server program can only realize the dialogue between the Server and a customer. In practical applications, a permanent program is often run on the Server, which can receive requests from multiple other clients and provide corresponding services. In order to realize the function of providing services to multiple customers on the Server side, it is necessary to transform the above program and realize the multi customer mechanism by using multithreading. The Server always monitors whether there is a client request on the specified port. Once the client request is monitored, the Server will start a special service thread to respond to the client's request, and the Server itself will enter the listening state immediately after starting the thread and wait for the arrival of the next client.

Summary: the implementation principle is not to close the socket, and then add multithreading

The following case uses Socket communication of TCP protocol

Long connection server

package chang;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//Customer service end
public class TCPClient {
    public static void main(String[] args) throws IOException {
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //Create a connection with the server
                        Socket socket =new Socket("127.0.0.1",8800);

                        OutputStream os = socket.getOutputStream();
                        String str="Hello server====:___:";
                        os.write(str.getBytes());

                        InputStream is=socket.getInputStream();
                        byte[] bytes=new byte[1024];
                        int len=is.read(bytes);
                        System.out.println(new String(bytes,0,len));

                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }





    }

}

client

package chang;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPServer {



    public static void main(String[] args) throws IOException {

        ServerSocket server=new ServerSocket(8800);
                while (true){
                     Socket socket=server.accept();

                     new  Thread(new Runnable() {
                         @Override
                         public void run() {
                             try {

                                 InputStream is=socket.getInputStream();
                                 byte[] bytes=new byte[1024];
                                 int len=is.read(bytes);
                                 System.out.println(new String(bytes,0,len));
                                 OutputStream os= socket.getOutputStream();
                                 os.write("Yes, thank you".getBytes());
                                 //Close flow
                                 os.flush();
                                 os.close();
                                 is.close();
                                 socket.close();
                             } catch (IOException e) {
                                 e.printStackTrace();
                             }


                         }
                     }).start();
                 }

        }

}

After the server is turned on, you can continuously use the client to request the server

Of course, the client can also implement a long connection. Just refer to the server. The code is almost the same, but note that the socket cannot be closed when using a long connection

That is, you cannot use this code socket.close();

The Socke of UDP protocol is the same. Just refer to the long link code above

Upload file case

Multiple users can upload to a server at the same time. The following is implemented by multithreading

client

package io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//Customer service end
public class TCPClient {
    public static void main(String[] args) throws IOException {

        new  Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileInputStream fis=new FileInputStream("src\\io\\client\\1.png");
                    //Create a connection with the server
                    Socket socket =new Socket("127.0.0.1",8811);
                    OutputStream os = socket.getOutputStream();
                    int len=0;
                    byte[] bytes=new byte[1024];
                    while ((len=fis.read(bytes))!=-1){
                        os.write(bytes,0,len);
                    }
                    socket.shutdownOutput();
                    InputStream is=socket.getInputStream();
                    byte[] bytes1=new byte[1024];
                    int len1=0;
                    while ((len1=is.read(bytes1))!=-1){
                        System.out.println(new String(bytes1,0,len1));
                    }
                    fis.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new  Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileInputStream fis=new FileInputStream("src\\io\\client\\1.png");
                    //Create a connection with the server
                    Socket socket =new Socket("127.0.0.1",8811);
                    OutputStream os = socket.getOutputStream();
                    int len=0;
                    byte[] bytes=new byte[1024];
                    while ((len=fis.read(bytes))!=-1){
                        os.write(bytes,0,len);
                    }
                    socket.shutdownOutput();
                    InputStream is=socket.getInputStream();
                    byte[] bytes1=new byte[1024];
                    int len1=0;
                    while ((len1=is.read(bytes1))!=-1){
                        System.out.println(new String(bytes1,0,len1));
                    }
                    fis.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

}

Server

package io;

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

public class TCPServer {


    public static void main(String[] args) throws IOException {

        ServerSocket server=new ServerSocket(8811);
        while (true){
        Socket socket=server.accept();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream is=socket.getInputStream();
                    File file=new File("src\\io\\server");
                    if(file.exists()){
                        file.mkdirs();
                    }

                    //Custom file name
                    String filename="it"+System.currentTimeMillis()+new Random().nextInt(99999)+".jpg";

                    FileOutputStream fos=new FileOutputStream(file+"\\"+filename);
                    int len=0;
                    byte[] bytes=new byte[1024];
                    while ((len=is.read(bytes))!=-1){
                        fos.write(bytes,0,len);
                    }

                    OutputStream os= socket.getOutputStream();
                    os.write("Upload succeeded".getBytes());
                    fos.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        }


    }
}

Start the server first, and then upload it on the client

Simulated web server

package Web;

import sun.security.util.Length;

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

public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8811);
        while (true) {
            Socket socket = server.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream is = socket.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        String line = br.readLine();
                        System.out.println(line);
                        String[] arr = line.split(" ");
                        //Gets the path requested in the web page
                        String htmlpath = arr[1].substring(1);
                        //Read the file of the requested path
                        FileInputStream fis = new FileInputStream(htmlpath);
                        OutputStream os = socket.getOutputStream();
                        //Fixed writing method for writing http protocol response header
                        os.write("HTTP/1.1 200 ok\r\n".getBytes());
                        os.write("Content-Type:text/html\r\n".getBytes());
                        //A blank line must be written, otherwise the viewer will not parse
                        os.write("\r\n".getBytes());

                        //Read the contents of the path file requested by the viewer to the viewer
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while ((len = fis.read(bytes)) != -1) {
                            os.write(bytes, 0, len);

                        }
                        os.flush();
                        fis.close();
                        socket.close();

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


                }
            }).start();
        }
    }


}

I created a normal java project and created a Web folder under src

This is my catalogue

Start the server first, and then enter in the browser

http://192.168.1.119:8811/src/Web/index.html

Change the ip address to your service

Like - collect - pay attention Easy to review and receive the latest content in the future If you have other questions to discuss in the comment area - or send me a private letter - you will reply as soon as you receive them Thank you for your cooperation. I hope my efforts will be helpful to you^_^

Posted by cafrow on Thu, 18 Nov 2021 23:32:15 -0800