springboot websocket

1.maven依赖

	<!--websocket-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>

2.编写配置

package com.sudy.chargerpad.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();
    }
}

3.编写服务端

package com.sudy.chargerpad.test;

import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/wstest")
@Service
public class WebSocketTest {
    //静态变量,用于记录当前在线连接数,应该把它设计成线程安全的
    private static int onlineCount = 0;
    //concurrent包的线程安全set,用来存放每个客户端对应的websocket对象
    private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为:"+getOnlineCount());
        try {
            sendMessage("有新连接加入了!!");
        }catch (Exception e){

        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有连接关闭!当前在线人数为:"+getOnlineCount());
    }

    /**
     *收到客户端发送信息后调用
     */
    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("来自客户端的消息:"+message);
        //群发消息
        for(WebSocketTest item:webSocketSet){
            try{
                //获取当前用户名称
//                String userName = item.getSession().getUserPrincipal().getName();
//                System.out.println(userName);
                item.sendMessage(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     *发生错误时调用
     */
    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("发送错误");
        error.printStackTrace();
    }
    public Session getSession(){
        return session;
    }
    //发送消息
    private void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }
    //返回在线数
    private static synchronized int getOnlineCount(){
        return onlineCount;
    }
    //当连接增加时
    private static synchronized void addOnlineCount(){
        WebSocketTest.onlineCount++;
    }
    //当连接减少时
    private static synchronized void subOnlineCount(){
        WebSocketTest.onlineCount--;
    }

}

编写测试界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport"
          content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <title>功率曲线</title>
    <script src="../ui/js/jquery-1.8.0.min.js"></script>
    <script>
        var socket;
        if (typeof (WebSocket) == "undefined") {
            console.log("遗憾:您的浏览器不支持WebSocket");
        } else {
            console.log("恭喜:您的浏览器支持WebSocket");

            //实现化WebSocket对象
            //指定要连接的服务器地址与端口建立连接
            //注意ws、wss使用不同的端口。我使用自签名的证书测试,
            //无法使用wss,浏览器打开WebSocket时报错
            //ws对应http、wss对应https。
            socket = new WebSocket("ws://192.168.3.25:8092/wstest");
            //连接打开事件
            socket.onopen = function () {
                appendMessage("Socket 已打开");
            };
            //收到消息事件
            socket.onmessage = function (msg) {
                console.log(msg)
                appendMessage(msg.data);

            };
            //连接关闭事件
            socket.onclose = function () {
                appendMessage('close')
            };
            //发生了错误事件
            socket.onerror = function () {
                appendMessage("Socket发生了错误");
            }

            //窗口关闭时,关闭连接
//            window.unload = function () {
//                socket.close();
//            };
            //监听窗口关闭事件,当窗口关闭时,主动关闭websocket连接
            //防止连接还没断开就关闭窗口,server会抛出异常
            window.onbeforeunload = function () {
                socket.close();
            }

        }
        //关闭连接
        function closeWebSocket(){
            socket.close();
        }
        //发送消息
        function sendMessage(){
            var message = $('#message').val();
            socket.send(message);
        }
        //将消息显示在网页上
        function appendMessage(message) {
            var content = $('#context').html()+"<br/>"+message;
            $('#context').html(content);
        }


    </script>
</head>
<body>
测试一下WebSocket 站点
<br/>
<input id="message" type="text"/>
<button onclick="sendMessage()">发送消息</button>
<button onclick="closeWebSocket()">关闭WebSocket 连接</button>
<div id="context"></div>

</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值