1: the webSocket

In single-machine mode, there is no way to support many clients, so cluster deployment is required, but there are problems with cluster deploymentCopy the code

2: Solve the distributed Session problem

Second, message distribution. For example, I send a message from client-1 to app-1. At this time, I only need to synchronize this message to app-2 and let app-2 push itCopy the code

3: the environment

1: JDK8 2: idea 3: Spring-cloud-AlibabaCopy the code

4: Starts the Nacos service

I downloaded the Nacos source package to run locally, version 1.4.1Copy the code

5: Implementation ideas

1: User 1 connects to machine A and sends A message. At this time, all users connected to machine A can receive the message, just like A single machine

2: At this point, when machine A sends this message to the client, we can get all instances of this service from Naocs. At this time, we only need to call an interface of other services to send this message to other machines

3: When other machines get this message, they call the WebSocket method and send this message to all users of the machine

6: Core code implementation

/** @param message */ @onMessage public void OnMessage (String message,Session Session) {log.info(" Message from client: {}",message); String id = session.getId(); Session BroadCastInfo(id + ": "+message); try{ log.info("session: {}" ,session); String uuid = userSession.get(session); String msg = uuid + "=" + message; / / user myDiscoveryClient sends a message to other nodes. The sendMsgToService (MSG); }catch (Exception e) { e.printStackTrace(); }}Copy the code
public void sendMsgToService(String msg) { InetAddress addr = null; try { addr = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } Map<String,String> params = new HashMap<>(); params.put("msg",msg); System.out.println(" the message to send is: "+ MSG); / / get all instances of the service from Nacos List < ServiceInstance > instances. = discoveryClient getInstances (SERVICE_ID); if(instances ! = null && ! instances.isEmpty()) { for(ServiceInstance instance : instances) { String host = instance.getHost(); int servicePort = instance.getPort(); Log.info (" server address :{} :{}",host,servicePort); String url = "http://socketOne:"+servicePort+"/index/send? msg={msg}"; // If (host! = addr.getHostAddress()) { restTemplate.getForObject(url,String.class,params); }}}}Copy the code
@Resource private WebSocketServer webSocketServer; @getMapping ("/send") @responseBody public String send(@requestParam (" MSG ") String MSG) webSocketServer.BroadCastInfo(msg); return "success"; }Copy the code

7: source code address

Gitee.com/baojh123/we…