WebSocket简单使用

WebSocket简单使用

后端:

加入依赖:
<!--websocket-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>2.0.4.RELEASE</version>
</dependency>
创建一个配置类:
@Bean
public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
}
controller层:
@RestController
@RequestMapping("/websocket")
public class TestController {
    @Autowired
    private WebSocket webSocket;

    @RequestMapping("/sendAllWebSocket")
    public String test(@RequestBody Map map) {
        webSocket.sendAllMessage((String) map.get("message"));
        return "websocket群体发送!";        
    }
    
    @RequestMapping("/sendOneWebSocket")
    public String sendOneWebSocket() {
        webSocket.sendOneMessage("", "");
        return "websocket单人发送";
    }
}
创建一个ws包:
@Component
@ServerEndpoint("/websocket/{id}/{name}")
//此注解相当于设置访问URL
public class WebSocket {

    //session可以使用redis存储,保证在集群部署时可以共享session
    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="id")String shopId,@PathParam("name")String name) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(shopId, session);
        System.out.println("【websocket消息】有新的连接,总数为:"+webSockets.size());
        sendAllMessage(name+":  进入直播间");
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    // 此为广播消息
    public void sendAllMessage(String message) {

        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String id, String message) {
        Session session = sessionPool.get(id);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

前端:

export default {
	created() { // 页面创建生命周期函数
      this.initWebSocket()
    },
    destroyed: function () { // 离开页面生命周期函数
      this.websocketclose();
    },
    methods:{
        initWebSocket: function () {
            var n = Math.floor(Math.random() * (100000 - 0) + 0)
            var name = "风雪";
            if (this.user.username != null){
                // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
                this.websock = new WebSocket("ws://localhost:8084/websocket/DPS" + n + "/" + this.user.username);
                // this.websock = new WebSocket("ws://localhost:9000/websocket/DPS007");
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onclose = this.websocketclose;
            }
        },
        websocketonopen: function () {
            console.log("WebSocket连接成功");
        },
        websocketonerror: function (e) {
            console.log("WebSocket连接发生错误");
        },
        websocketonmessage: function (e) {  //服务器返回的信息
            // var da = JSON.parse(e.data);
            console.log(e.data);
            this.addToList(e.data)    //加入弹幕
            this.list.push({          //加入消息框
                name:'',
                message: e.data
            })
            console.log(this.list)
            // this.message = da;
        },
        websocketclose: function (e) {
            console.log("connection closed (" + e + ")");
        },
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值