Spring boot 整合 webSocket

2 篇文章 0 订阅

1.pom.xml添加websocket依赖

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


2.创建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
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}


3.创建websocket服务端类

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
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.springframework.stereotype.Component;
 
@Component
@ServerEndpoint("/websocket/{id}/{xm}")
public class WebSocketServer {
 
    /**
     * 所有在线会话
     */
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();
 
    /**
     * 连接成功
     */
    @OnOpen
    public void onOpen(@PathParam(value = "id") String id, Session session) {
        onlineSessions.put(id, session);
        System.out.println("用户 "+id+" 上线!当前在线 "+onlineSessions.size()+" 人");
    }
 
    /**
     * 客户端发送消息调用
     */
    @OnMessage
    public void onMessage(@PathParam(value = "id") String id,@PathParam(value = "xm") String xm, Session session, String msg) throws IOException {
        if(msg.startsWith("P:")){
            //私聊(格式:P:sendUserId-私聊信息)
            String sendUserId = msg.split(":")[1].split("-")[0];
            msg = msg.split(":")[1].split("-")[1];
            sendtoUser(msg,id,sendUserId,xm);
        }else{
            //群聊
            sendMessageToAll(msg,xm);
        }
    }
 
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam(value = "id") String id, Session session) {
        onlineSessions.remove(id);
        System.out.println("用户 "+id+" 下线!当前在线 "+onlineSessions.size()+" 人");
    }
 
    /**
     * 连接错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
 
    /**
     * 发送信息给所有人
     */
    private static void sendMessageToAll(String msg, String xm) {
        onlineSessions.forEach((id, session) -> {
            try {
                session.getBasicRemote().sendText(xm+":"+msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
 
    /**
     * 发送信息给指定ID用户
     * @param id:用户id
     * @param sendUserId:发送给用户id
     */
    public void sendtoUser(String msg, String id, String sendUserId, String xm) throws IOException {
        if (onlineSessions.get(sendUserId) != null) {
            onlineSessions.get(sendUserId).getBasicRemote().sendText(xm+":"+msg);
            onlineSessions.get(id).getBasicRemote().sendText(xm+":"+msg);    
        } else {
            //如果用户不在线则返回不在线信息给自己
            onlineSessions.get(id).getBasicRemote().sendText("当前用户不在线");
        }
    }
 
}


4.前端页面和JS

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>聊天室</title>
<script src="/script/jquery.1.12.4.min.js"></script>
</head>
<body style="text-align: center;">
    <span>聊天室</span>  
    <input type="hidden" id="xm" th:value="${session.xm}">
    <input type="hidden" id="yhbh" th:value="${session.yhbh}">
    <div id="content" style="margin-left:auto;margin-right:auto;width:20%;height:500px;border: 1px solid #A9A9A9;text-align: left;"></div></br>
    <textarea style="width: 20%;" rows="3" id="contentInp"></textarea>
    <div>
        <button class="btn btn-danger" onclick="doSend();">发送消息</button>
        <button class="btn btn-danger" onclick="doClear();">清空会话框</button>
        <button onclick="doClose();">退出聊天</button>
    </div>
</body>
<script>
    var yhbh = $("#yhbh").val();
    var xm = $("#xm").val();
    var ws = new WebSocket("ws://localhost:8081/websocket/"+yhbh+"/"+xm); 
    
    $(function(){
        $("#contentInp").keyup(function(evt){
            if(evt.which == 13){ //enter键发送消息
                doSend();
            }
        });
    })
    
    ws.onopen = function(){
        console.log('连接成功!');
    }
    
    // 从服务端接收到消息,将消息回显到聊天记录区
    ws.onmessage = function(evt){
        var v = $("#content").html() + evt.data +"<br/>"; 
        $("#content").html(v);
    }
    
    ws.onerror = function(){
        console.log('连接失败!');
    }
    
    ws.onclose = function(){
        console.log('连接关闭!');
    }
    
    // 注销登录
    function doClose(){
        ws.close();
    }
    
    // 发送消息
    function doSend(){
        var msg = $.trim($("#contentInp").val());
        if(msg == ''){
            alert("请输入消息!");
        }else{
            ws.send(msg); 
            $("#contentInp").val("");    
        }
    }
    
    //清空消息
    function doClear(){
        $("#content").empty();
    }
</script>
</html>

 

转载于:https://blog.csdn.net/rexueqingchun/article/details/97640315

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值