netty socket simple realization customer service chat function detailed explanation (including Android client, java client, Java background program)

According to the previous article: https://blog.csdn.net/qq_41966009/article/details/104441452 Write the corresponding details according to the corresponding functions.

1. The client and server communicate with the background server (java background) respectively

1.1 communication between client (Android client) and background server (java background)

First, create a ChatApplication class, which mainly implements the following functions, and is convenient to use Socket in MainActivity

	IO.Options options = new IO.Options();
//    private SocketIo
    private Socket mSocket;
   private Socket mSocket;
    {
        try {
            options.reconnectionAttempts = 2;
            options.reconnectionDelay = 1000;//Time interval of failed reconnection
            options.timeout = 500;//Connection timeout (ms)
//           Under the constants class, there is a public static string chat server URL, which stores the IP address we need to connect.
            mSocket = IO.socket(Constants.CHAT_SERVER_URL,options);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    //Return the created Socket
    public Socket getSocket() {
        return mSocket;
    }

Register various kinds of monitoring in onCreate of MainActivity

		//All kinds of listening events are listening, including written listening and customized listening
		//The ChatApplication class is above
		//If there is an error in the following sentence, please check whether your project is Android X. if not, modify it according to the corresponding package.
        ChatApplication app = (ChatApplication) getApplication();
        mSocket = app.getSocket();
        //Connection monitoring registration. If an error is reported, please check the problem in order according to the error
        mSocket.on(Socket.EVENT_CONNECT,onConnect);
        mSocket.on(Socket.EVENT_ERROR,onEvent_Error);
        mSocket.on(Socket.EVENT_CONNECT_ERROR,onEvent_Connect_Error);
        //Get the Id of customer service
        mSocket.on("getStaffId"+userId,getStaffId);
        //Open connection
        mSocket.connect();

If it is written here, after the implementation of corresponding monitoring, you can start the development of java background. At this point, we will create a Maven project. Add the following dependencies to the pom.xml file. It may be a little slow. Wait a little bit.

  <dependencies>
        <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.17</version>
        </dependency>

        <dependency>
            <groupId>io.socket</groupId>
            <artifactId>socket.io-client</artifactId>
            <version>1.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.2</version>
        </dependency>
    </dependencies>

Create a Server class and implement the java background function

public static void main(String [] args){
 //Set address and port
        Configuration config = new Configuration();
        //Please refer to my previous article to set Ip address and why it is 192.168.3.73 instead of localhost
        config.setHostname("192.168.3.73");
        //Set port
        config.setPort(9000);
        SocketIOServer server = new SocketIOServer(config);
        //Service monitoring, monitoring whether there is user access
        server.addConnectListener(new ConnectListener() {
            // Add client connection listener
            public void onConnect(SocketIOClient client) {
                String sa = client.getRemoteAddress().toString();
                String clientIp = sa.substring(1,sa.indexOf(":"));//Get ip of client connection
                String clientPort = sa.substring(sa.indexOf(":"));//Get the port of the client connection
                System.out.println("First The server receives the connection information of the client as:"+sa+"----ip:"+clientIp+"   port:"+clientPort);
                //I don't know how to correspond with the Client. The best way is to write the corresponding function by myself. If the Client connects successfully, send a string "hello" to the Client
                client.sendEvent("connected", "hello I am Server,You have successfully connected");
            }
        });
		//At this point, the server-side service has been started. We use the send function to write a monitor to see if the communication between the server-side and the user-side is successful
        server.start();
        
//The messages sent by the default message event send are listened to and processed by this listener. The personal user information sent by the user is processed here
        server.addEventListener("message", String.class, new DataListener<String>() {
            @Override
            public void onData(SocketIOClient socketIOClient, String s, AckRequest ackRequest) throws Exception {
               System.out.println("Receive messages from users"+s);
             }
        });
}

So far, the basic java background and client have been built (pure test, the actual code should not be written in this way)
We can send a piece of data to the java background on the Android client to see if the communication is successful

  //A click event of Android client can also be used to test whether the connection with java background is successful
  //The number here is the ID of our user, which is convenient for subsequent testing.
  mSocket.send("2017030401037: Hello");

java background display

1.2 communication between customer service terminal (Android client) and background server (java background)

Similarly, according to Android code, after modification, the communication between customer service end and background server can be completed.

2. If the number of clients accessing back-end servers is greater than that of clients accessing back-end servers, or vice versa. Redundant users or redundant customer service will join the corresponding "team" to queue (pile in). Whoever is in front of the team will communicate with users or customer service in advance.

First of all, I will send a message to tell the server who "I" is
Android client:

 //Here, 1 represents that I am a request sent by the client, and I have my ID (usually the account is used as the Id)
 mSocket.send("1:"+userId);

java customer service terminal:

 //The 0 here means that I am the request from the customer service terminal, and I have my ID (usually the account number is used as the Id)
 socket.send("0:"+staffId);

The java background server will analyze who the current user is according to the received data, and reasonably let the customer service know who their customer service users are according to the current customer service quantity. If the number of customer service is less than the user, the user will enter his corresponding "team" to queue (in the heap). If the number of user is less than the customer service, the customer service will enter his corresponding "team" to queue (in the heap). If a new customer or user requests to join, there will be a team leader element (the one waiting the longest) in the team to agree with it.
Attach my own java background processing send function test code:

 //The messages sent by the default message event send are listened to and processed by this listener. The personal user information sent by the user is processed here
        server.addEventListener("message", String.class, new DataListener<String>() {
            @Override
            public void onData(SocketIOClient socketIOClient, String s, AckRequest ackRequest) throws Exception {
                //Get type: if getType is 1, then it is the user; if it is 0, then it is customer service
                String getType=s.substring(0,s.indexOf(":"));
                //Starting to get ID Id1 is to get the string before the current ":", which is mainly used to know the length
                String Id1=s.substring(0,s.indexOf(":"));
                //After obtaining the length of Id1, the obtained ID is intercepted according to the substring function
                String Id =s.substring(Id1.length()+1,s.length());
                System.out.println("Get to type: "+getType);
                System.out.println("Get to id: "+Id);
                //1. Users view Android code
                //0 is customer service check Java code
                if(Integer.parseInt(getType)==1){
                    System.out.println("Personal information sent by users"+s);
                    //If the element in the customer service team is greater than 0, it means that there is a customer service waiting for the user. At this time, a user will be assigned to the customer service team
                    if(staffId.size()>0){
                        //Get the Id of the customer service in the heap
                        String getStaffId=staffId.get(0).toString();
                        //Send to customer service
                        System.out.println("To be sent to customer service users Id by:"+Id);
                        //Send it to customer service to let customer service know who its users are
                        server.getBroadcastOperations().sendEvent("getUserId"+getStaffId,Id);
                        //Send it to the user to let the user know who his customer service is          
                    server.getBroadcastOperations().sendEvent("getStaffId"+Id,getStaffId);

                        //Remove the first customer service to enter -- FIFO algorithm
                        staffId.remove(0);
                    }else {
                        System.out.println("User entry  Id:"+Id);
                        userId.add(Id);
                    }
                }else if(Integer.parseInt(getType)==0){
                    System.out.println("Personal information from customer service"+s);
                    if(userId.size()>0){
                        //Get the Id of the user in the heap
                        String getUserId=userId.get(0).toString();
                        //Send to user
                        System.out.println("To be sent to customer service Id by:"+Id);
                  
                        server.getBroadcastOperations().sendEvent("getStaffId"+getUserId,Id);

                        String user1=userId.get(0).toString();
                     
                        server.getBroadcastOperations().sendEvent("getUserId"+Id,user1);

                        userId.remove(0);
                    }else {
                        System.out.println("Customer service entry  Id:"+Id);
                        staffId.add(Id);
                    }
                }else if(Integer.parseInt(getType)==2){
                        System.out.println("User has successfully accessed");
                }else {
                    System.out.println("Unknown identity message"+s+"Refuse to deal with");
                }
                System.out.println("**********************************");
            }
        });

The above implementation enables users to know who their customer service is (they get their own information (Id)), and customer service knows who their users are

3. Communication and chat between client and customer service

What I'm doing here is the worst. I'm only limited to functions. I hope you can tell me the best way to communicate between the client and the customer service.
Since customer service needs to communicate with users, the server needs to monitor accordingly:

   //Receive customer service send message monitor and send to user
        server.addEventListener("submitMessageToUser", String.class, new DataListener<String>() {
            @Override
            public void onData(SocketIOClient socketIOClient, String s, AckRequest ackRequest) throws ClassNotFoundException {
                String getAllMessage=s;
                String getStaffId=getAllMessage.substring(0,getAllMessage.indexOf(":"));
                String getMessage1=s.substring(0,s.indexOf(":"));
                String getMessage=s.substring(getMessage1.length()+1,s.length());
                System.out.println("Received a message from customer service"+s+"    Received from customer service Id:"+getStaffId+"    Receive message to send to user:"+getMessage);
                server.getBroadcastOperations().sendEvent("borcast:"+getStaffId,getMessage);
            }
        });

        //Receiving users send messages to monitor and then send them to customer service
        server.addEventListener("submitMessageToStaff", String.class, new DataListener<String>() {
            @Override
            public void onData(SocketIOClient socketIOClient, String s, AckRequest ackRequest) throws ClassNotFoundException {
                String getAllMessage=s;
                String getUserId=s.substring(0,s.indexOf(":"));
                String getMessage1=s.substring(0,s.indexOf(":"));
                String getMessage=getAllMessage.substring(getMessage1.length()+1,s.length());
                System.out.println("Receive message from user"+s+"    Received from user Id:"+getUserId+"    Receive information to be sent to customer service:"+getMessage);
                server.getBroadcastOperations().sendEvent("borcast:"+getUserId,getMessage);
            }
        });

Because the last section has described that the client and customer service get the information of the people they want to communicate with, so I use the emit function to send messages
Android client:

  //I need to send out my information and Id. Id tells customer service who I am, and information tells others what I want to say to customer service
  mSocket.emit("submitMessageToStaff", userId+":"+message);

java customer service terminal

  //I need to send out my information and Id. Id tells the user who I am, and the information tells others what I want to say to customer service
  socket.emit("submitMessageToUser",staffId+":"+s);

According to the above monitoring of the server, you can realize the mutual transmission of messages.

4. Picture and text explanation: https://blog.csdn.net/qq_41966009/article/details/104441452

All code addresses of Github, including Android client, java customer service, and java backend:

Published 30 original articles, won praise 2, visited 3484
Private letter follow

Keywords: Java socket Android less

Added by Pjack125 on Sat, 22 Feb 2020 09:10:39 +0200