WebSocket简单实现( + SpringBoot)

pom.xml

		<!--WebSocket依赖-->
		<dependency>
		    <groupId>javax.websocket</groupId>
		    <artifactId>javax.websocket-api</artifactId>
		    <version>1.1</version>
		    <scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>

如何调用service方法去操作数据?
       实现 ApplicationContextAware 接口
       添加静态属性 private static ApplicationContext applicationContext;
       实现其 setApplicationContext 方法引入 applicationContext ,通过其 getBean(***Service.class) 方法就能调用 bean 了

MyWebSocketServer

package com.example.demo.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/** @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端*/
@ServerEndpoint(value = "/websocket/{username}")
@Component
public class MyWebSocketServer {

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

//    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
//    private static CopyOnWriteArraySet<MyWebSocketServer> webSocketSet = new CopyOnWriteArraySet<MyWebSocketServer>();

    public static ConcurrentMap<String, MyWebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    private String username;


    private static final Logger log = LoggerFactory.getLogger(MyWebSocketServer.class);


    /**
     * 连接建立成功调用的方法 
     * TODO username 尽量存不重复的
     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="username")String username) throws IOException {
        this.session = session;
        this.username= username;
        log.info("onOpen"+session.getId());

        webSocketMap.put(username,this);
        addOnlineCount();
        log.info("有新连接加入!当前在线人数为:" + getOnlineCount());

        this.session.getBasicRemote().sendText("已成功调用!");//TODO 这里用的是查询记录在数据库的内容
    }

    /**
    * 连接关闭后触发的方法
    */
    @OnClose
    public void onClose(@PathParam("username") String username){
        //从map中删除
        webSocketMap.remove(username);
        log.info("====== onClose: "+ username +" ======");

        subOnlineCount();
        log.info("有一连接关闭!当前在线人数为:" + getOnlineCount());
    }

    /**
    * 收到客户端消息后调用的方法
    * @param message 客户端发送过来的消息
    */
    @OnMessage
    public void onMessage(String message){
        log.info("收到消息:"+message);
    }
    
    /**
    * 发生错误时触发的方法
    */
    @OnError
    public void onError(Throwable error){
        log.error("websocket发生错误:" + error);
    }


    // 此为广播消息
    public void sendAllMessage(String message) {
        for (MyWebSocketServer myWebSocketServer : webSocketMap.values()) {
            log.info("【websocket消息】广播消息:"+message);
            myWebSocketServer.session.getAsyncRemote().sendText(message);
        }
    }

    // 此为单点消息
    public void sendOneMessage(String receiver, String message) {
        if(webSocketMap == null){
            log.error("MyWebSocket 为 null");
        }
        if(webSocketMap.containsKey(receiver)){//或者 webSocketMap.get(username) != null
            webSocketMap.get(receiver).session.getAsyncRemote().sendText(message);
            log.info("【websocket消息】单点消息已发送给 "+receiver);
        } else {
            log.warn("未找到接收者!");
        }
//        for (MyWebSocketServer myWebSocketServer : webSocketMap.values()) {
//            if(myWebSocketServer.username.equals(receiver)){
//                myWebSocketServer.session.getAsyncRemote().sendText(message);
//                log.info("【websocket消息】单点消息已发送给 "+receiver);
//                return;
//            }
//        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocketServer.onlineCount--;
    }

}

WebSocketConfig

package com.example.demo.websocket;

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会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

WebSocketController

package com.example.demo.controller;

import com.example.demo.websocket.MyWebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/webSocket",produces = "application/json;charset=utf-8")
public class WebSocketController {

    @Autowired
    private MyWebSocketServer myWebSocketServer;

    @RequestMapping("/testWebSocket")
    public ResponseEntity<String> testWebSocket(String username){
        myWebSocketServer.sendOneMessage(username,"测试 WebSocket .....");
        return ResponseEntity.status(HttpStatus.OK).body("testWebSocket 测试成功!");
    }


}

weChat.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Web sockets test</title>
    <script type="text/javascript">
        var ws;

        function login() {
            if (!ws) {
                var user = document.getElementById("name").value;
                try {
                    ws = new WebSocket("ws://127.0.0.1:8081/websocket/" + user);//连接服务器
                    ws.onopen = function (event) {
                        console.log("已经与服务器建立了连接...");
                        alert("登陆成功,可以开始聊天了")
                    };
                    ws.onmessage = function (event) {
                        console.log("接收到服务器发送的数据..." + event.data);
                        document.getElementById("info").innerHTML += event.data + "<br>";
                    };
                    ws.onclose = function (event) {
                        console.log("已经与服务器断开连接...");
                    };
                    ws.onerror = function (event) {
                        console.log("WebSocket异常!");
                    };
                } catch (ex) {
                    alert(ex.message);
                }
                document.getElementById("login").innerHTML = "退出";
            } else {
                ws.close();
                ws = null;
            }
        }

        function SendData() {
            var data = document.getElementById("data").value;
            try {
                ws.send(data);
            } catch (ex) {
                alert(ex.message);
            }
        };

    </script>
</head>
<body>
<input id="name" value="" placeholder="用户名">
<button id="login" type="button" onclick="login()" value="">登陆</button>
<br/><br/>
<input id="data">
<button type="button" onclick='SendData();'>发送消息</button>
<br/><br/>
<div id="info">

</div>
</body>
</html>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值