Springboot整合Webscoket

1、maven导入相应的依赖

 <!-- websocket依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>LATEST</version>
        </dependency>

2、创建WebSocketConfig配置类

package cn.orz.config;


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

@Configuration
@EnableWebSocket // 启用websocket
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter getServerEndpointExporter() { //服务终端
        return new ServerEndpointExporter();
    }
}

3、创建Websocket类

package cn.orz.Socket;


import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
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;


@Component
@ServerEndpoint("/websocket/{userId}")
public class Websocket {

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

    //记录每个用户下多个终端的连接
    private static Map<Long, Set<Websocket>> userSocket = new HashMap<>();

    //需要session来对用户发送数据, 获取连接特征userId
    private Session session;
    private Long userId;

    /**
     * @Title: onOpen
     * @Description: websocekt连接建立时的操作
     * @param @param userId 用户id
     * @param @param session websocket连接的session属性
     * @param @throws IOException
     */
    @OnOpen
    public void onOpen(@PathParam("userId") Long userId,Session session) throws IOException {
        this.session = session;
        this.userId = userId;
        onlineCount++;
        //根据该用户当前是否已经在别的终端登录进行添加操作
        if (userSocket.containsKey(this.userId)) {
            logger.debug("当前用户id:{}已有其他终端登录",this.userId);
            userSocket.get(this.userId).add(this); //增加该用户set中的连接实例
        }else {
            logger.debug("当前用户id:{}第一个终端登录",this.userId);
            Set<Websocket> addUserSet = new HashSet<>();
            addUserSet.add(this);
            userSocket.put(this.userId, addUserSet);
        }
        logger.debug("用户{}登录的终端个数是为{}",userId,userSocket.get(this.userId).size());
        logger.debug("当前在线用户数为:{},所有终端个数为:{}",userSocket.size(),onlineCount);
    }

    /**
     * @Title: onClose
     * @Description: 连接关闭的操作
     */
    @OnClose
    public void onClose(){
        //移除当前用户终端登录的websocket信息,如果该用户的所有终端都下线了,则删除该用户的记录
        if (userSocket.get(this.userId).size() == 0) {
            userSocket.remove(this.userId);
        }else{
            userSocket.get(this.userId).remove(this);
        }
        logger.debug("用户{}登录的终端个数是为{}",this.userId,userSocket.get(this.userId).size());
        logger.debug("当前在线用户数为:{},所有终端个数为:{}",userSocket.size(),onlineCount);
    }



    /**
     * @Title: onMessage
     * @Description: 收到消息后的操作
     * @param @param message 收到的消息
     * @param @param session 该连接的session属性
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.debug("收到来自用户id为:{}的消息:{}",this.userId,message);
        if(session ==null)  logger.debug("session null");
    }

    /**
     * @Title: onError
     * @Description: 连接发生错误时候的操作
     * @param @param session 该连接的session
     * @param @param error 发生的错误
     */
    @OnError
    public void onError(Session session, Throwable error){
        logger.debug("用户id为:{}的连接发送错误",this.userId);
        error.printStackTrace();
    }

    /**
     * @Title: sendMessageToUser
     * @Description: 发送消息给用户下的所有终端
     * @param @param userId 用户id
     * @param @param message 发送的消息
     * @param @return 发送成功返回true,反则返回false
     */
    public Boolean sendMessageToUser(Long userId,String message){
        if (userSocket.containsKey(userId)) {

            logger.debug(" 给用户id为:{}的所有终端发送消息:{}",userId,message);
            for (Websocket WS : userSocket.get(userId)) {
                logger.debug("sessionId为:{}",WS.session.getId());
                try {
                    WS.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            return true;
        }

        logger.debug("发送错误:当前连接不包含id为:{}的用户",userId);
        return false;
    }

}


4、创建消息服务类

package cn.orz.Socket;


import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
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;


@Component
@ServerEndpoint("/websocket/{userId}")
public class Websocket {

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

    //记录每个用户下多个终端的连接
    private static Map<Long, Set<Websocket>> userSocket = new HashMap<>();

    //需要session来对用户发送数据, 获取连接特征userId
    private Session session;
    private Long userId;

    /**
     * @Title: onOpen
     * @Description: websocekt连接建立时的操作
     * @param @param userId 用户id
     * @param @param session websocket连接的session属性
     * @param @throws IOException
     */
    @OnOpen
    public void onOpen(@PathParam("userId") Long userId,Session session) throws IOException {
        this.session = session;
        this.userId = userId;
        onlineCount++;
        //根据该用户当前是否已经在别的终端登录进行添加操作
        if (userSocket.containsKey(this.userId)) {
            logger.debug("当前用户id:{}已有其他终端登录",this.userId);
            userSocket.get(this.userId).add(this); //增加该用户set中的连接实例
        }else {
            logger.debug("当前用户id:{}第一个终端登录",this.userId);
            Set<Websocket> addUserSet = new HashSet<>();
            addUserSet.add(this);
            userSocket.put(this.userId, addUserSet);
        }
        logger.debug("用户{}登录的终端个数是为{}",userId,userSocket.get(this.userId).size());
        logger.debug("当前在线用户数为:{},所有终端个数为:{}",userSocket.size(),onlineCount);
    }

    /**
     * @Title: onClose
     * @Description: 连接关闭的操作
     */
    @OnClose
    public void onClose(){
        //移除当前用户终端登录的websocket信息,如果该用户的所有终端都下线了,则删除该用户的记录
        if (userSocket.get(this.userId).size() == 0) {
            userSocket.remove(this.userId);
        }else{
            userSocket.get(this.userId).remove(this);
        }
        logger.debug("用户{}登录的终端个数是为{}",this.userId,userSocket.get(this.userId).size());
        logger.debug("当前在线用户数为:{},所有终端个数为:{}",userSocket.size(),onlineCount);
    }



    /**
     * @Title: onMessage
     * @Description: 收到消息后的操作
     * @param @param message 收到的消息
     * @param @param session 该连接的session属性
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.debug("收到来自用户id为:{}的消息:{}",this.userId,message);
        if(session ==null)  logger.debug("session null");
    }

    /**
     * @Title: onError
     * @Description: 连接发生错误时候的操作
     * @param @param session 该连接的session
     * @param @param error 发生的错误
     */
    @OnError
    public void onError(Session session, Throwable error){
        logger.debug("用户id为:{}的连接发送错误",this.userId);
        error.printStackTrace();
    }

    /**
     * @Title: sendMessageToUser
     * @Description: 发送消息给用户下的所有终端
     * @param @param userId 用户id
     * @param @param message 发送的消息
     * @param @return 发送成功返回true,反则返回false
     */
    public Boolean sendMessageToUser(Long userId,String message){
        if (userSocket.containsKey(userId)) {

            logger.debug(" 给用户id为:{}的所有终端发送消息:{}",userId,message);
            for (Websocket WS : userSocket.get(userId)) {
                logger.debug("sessionId为:{}",WS.session.getId());
                try {
                    WS.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            return true;
        }

        logger.debug("发送错误:当前连接不包含id为:{}的用户",userId);
        return false;
    }

}


5、创建MessageController类

package cn.orz.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("message")
public class MessageController {

    @Autowired
    private WSMessageService wsMessageService;

    private Logger logger = LoggerFactory.getLogger(MessageController.class);

    //请求入口
    @RequestMapping(value="/SendWS",method= RequestMethod.GET)
    @ResponseBody
    public String TestWS(@RequestParam(value="userId") Long userId,
                         @RequestParam(value="message") String message){


        logger.warn("收到发送请求,向用户{}的消息:{}",userId,message);
        if(wsMessageService.sendToAllTerminal(userId, message)){

            return "success";
        }else{

            return "error";
        }
    }
}


6.网页测试

<html>
<head>
    <title>Title</title>

    <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
    <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <title>webSocket-用户66</title>
    <script type="text/javascript">
        $(function() {
            var websocket;
            if('WebSocket' in window) {
                console.log("此浏览器支持websocket");
                websocket = new WebSocket("ws://127.0.0.1:8888/websocket/2");
            } else if('MozWebSocket' in window) {
                alert("此浏览器只支持MozWebSocket");
            } else {
                alert("此浏览器只支持SockJS");
            }
            websocket.onopen = function(evnt) {
				
				
                $("#tou").html("链接服务器成功!")
            };
            websocket.onmessage = function(evnt) {
                $("#msg").html($("#msg").html() + "
"
+ evnt.data); }; websocket.onerror = function(evnt) {}; websocket.onclose = function(evnt) { $("#tou").html("与服务器断开了链接!") } $('#send').bind('click', function() { send(); }); function send() { if(websocket != null) { var message = "用户B---:"+document.getElementById('message').value; $.ajax({ url:"http://localhost:8888/message/SendWS?userId=2&message=" +message, type:"GET", success: function(result){ } }); $.ajax({ url:"http://localhost:8888/message/SendWS?userId=1&message=" +message, type:"GET", success: function(result){ } }); } else { alert('未与服务器链接.'); } } }); </script> </head> <body> <div class="page-header" id="tou"> webSocket多终端聊天测试 </div> <div class="well" id="msg"></div> <div class="col-lg"> <div class="input-group"> <input type="text" class="form-control" placeholder="发送信息..." id="message"> <span class="input-group-btn"> <button class="btn btn-default" type="button" id="send" >发送</button> </span> </div> </div> </body> </html>

你可能感兴趣的:(spring,boot,websocket,java)