socket server message to the designated client

A. Demand

If that demand. When a plurality of clients connected to the server, the server how to send a message to the specified client.

 

II. Solution

The core idea: On the server side, the need to save different client socket client list and related information. 

socket containing sender and recipient ip and port number, the message can be sent by the client to the designated socket.

 

After checking the data, get the following solutions:

 

When a user is connected, immediately sends its unique ID to the server, the server ID and the map is stored with the corresponding socket when sending a message to the client, you can ID, find the corresponding socket, and then send the message.

If the client ip fixed, each server will receive a Socket with Map

III. Practice

Description: The first solution, the analog server sends a message to the specified client.

 

Cycle monitor server, the first server comes in, send its own sequence number, the second coming, socke traversal list, send sequence number corresponding to each client in the list, so as to achieve the specified server sends the client a message function. 

Service-Terminal

package server;

import java.io. * ;
import java.net.*;
import java.util.HashMap;

/**
 * Main function, functional server sends a message to the specified client.
 * The client written in python
 * @author dingding
 *
 */

public class Run {
    private final static int PORT = 30000;
    public static HashMap<String, Socket> socketList = new HashMap<>();
    public static String channelToken;  //socket 令牌
    private static BufferedReader bufferedReader;

    public static void main(String[] args) {
        try {
            ServerSocket server =  new ServerSocket(PORT);
            . The System OUT .println ( " Server IS listenning ... " );
             the while ( to true ) { // continuous cycle always waiting for new clients to access the server 
                the Socket = the clientSocket, server.accept ();
                bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                channelToken = bufferedReader.readLine();
                socketList.put (channelToken, the clientSocket,);    // save session ID and Socket
                 // System.out.println (socketList.get (channelToken));
                 // System.out.println (socketList); 
                new new ServerThread (the clientSocket,, socketList) ;
            }
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}
package server;

import java.io. * ;
import java.net.*;
import java.util. * ;


public class ServerThread extends Thread{
    private Socket client;
    private PrintWriter out;
    private  HashMap<String, Socket> clientList = new HashMap<>();

    public ServerThread(Socket socket,HashMap<String, Socket> socketList) throws IOException{
        super();
        client = socket;
        clientList = socketList;

        start();
    }

    @Override
    public void run(){
        Socket socket;
        System.out.println("Client: "+getName()+" come in...");

        // whenever the client connection, and respond to the corresponding client 
        the Iterator <HashMap.Entry <String, the Socket entries It >> = clientList.entrySet () Iterator ();. 
         The while (entries.hasNext ()) {
            HashMap.Entry<String, Socket> entry = entries.next(); 
            System.out.println(entry.getKey());
            if (!String.valueOf(entry.getKey()).equals("")) {
                System.out.println(entry.getValue());
                System.out.println("-------------");
                socket = entry.getValue();
                if (socket!=null) {
                    try {
                        out = new PrintWriter(socket.getOutputStream());  //回复client的ID
                        out.println(entry.getKey());
                        out.flush();
                    } catch (IOException e) {
                        e.printStackTrace ();
                    }
                }
            }
        }
    }
}

Two clients to simulate two scenarios python client. 

#coding = utf-8
import socket
import threading

HOST = "localhost"
PORT = 30000

sock = socket.socket, (socket.AF_INET, socket.SOCK_STREAM),
sock.connect((HOST, PORT))  

def test():
    socketID = 'I am 111'    
    sock.sendall((socketID+'\r').encode())
    while True:
        data = sock.recv(1024).decode()
        print('from line: '+data)
    sock.close()

if __name__ == '__main__':
    test()
#coding = utf-8
import socket
import threading

HOST = "localhost"
PORT = 30000

sock = socket.socket, (socket.AF_INET, socket.SOCK_STREAM),
sock.connect((HOST, PORT))
def test():
    socketID = 'I am 000'    
    sock.sendall((socketID+'\r').encode())
    while True:
        data = sock.recv(1024).decode()
        print('from line: '+data)
    sock.close()

if __name__ == '__main__':
    test()

IV. Summary

socket server message to the designated client, not much to online resources, mostly on server mass. Here are concrete solutions, and through examples demonstrate the feasibility of the program.

 

Sometimes more information see, the more do not understand this is not always a good thing. 

This time we need to calm down reasonable grounds for thinking, then specific solutions, programming. 

Practice is the sole criterion for testing truth design code when you are away from the success a step closer.

references

  1. java socket programming, how to take the initiative to send a message to the specified server ip address of the client
  2. socket server to specify how to handle messaging client
  3. socket server to specify how to handle messaging client

--------------------- 

Author: Deen12520 

Source: CSDN 

Original: https: //blog.csdn.net/dingding_12345/article/details/72790839 

Disclaimer: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/Im-Victor/p/11068291.html