Spring Boot笔记-WebSocket的使用

程序结构如下:

关键源码如下:

WebSocketConfig.java

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {

        return new ServerEndpointExporter();
    }

}

MyController.java

package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.service.WsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    WsService wsService;

    @PostMapping("/msg")
    public Object sendMsg(@RequestBody String req){

        JSONObject jsonObject = JSONObject.parseObject(req);
        System.out.println(jsonObject.getString("msg"));
        wsService.sendInfo(jsonObject.getString("msg"));

        return "success";
    }
}

WsService.java

package com.example.demo.service;

import com.example.demo.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class WsService {

    @Autowired
    public WebSocketServer webSocketServer;

    @Async
    public void sendInfo(String message) {

        webSocketServer.sendInfo(message);
    }
}

WebSocketServer.java

package com.example.demo.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

@Component
@ServerEndpoint("/ws/{token}")
public class WebSocketServer {

    //每个客户端有一个token
    private String token = "";

    private static HashMap<String, Session> map = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token){

        map.put(token, session);
        this.token = token;
        System.out.println("新连接:" + session);
    }

    @OnClose
    public void onClose(Session session){

        map.remove(this.token);
        System.out.println("连接关闭:" + session);
    }

    @OnError
    public void onError(Session session, Throwable error){

        System.out.println("错误:" + session + "," + error);
    }

    public void onMessage(String message, Session session){

        System.out.println("接收到消息:" + message);
    }

    //群发
    public void sendInfo(String message){

        for (String token : map.keySet()) {
            Session session = map.get(token);
            try {
                session.getBasicRemote().sendText(message);
            }
            catch (IOException e) {

                e.printStackTrace();
            }
        }
    }
}

application.properties

server.port=8880

源码打包下载地址:

https://github.com/fengfanchen/Java/tree/master/WebServiceDemo

 

 

 

相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页