SpringBoot整合WebSocket实现群聊和私聊

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>
发布了95 篇原创文章 · 获赞 131 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/rexueqingchun/article/details/97640315