当前位置: 首页>后端>正文

【详细】Spring完美整合WebSocket通讯

一. 效果演示

【详细】Spring完美整合WebSocket通讯,【详细】Spring完美整合WebSocket通讯_websocket,第1张

直入主题,呈上教程↘↘↘

二. 加入依赖包

首先添加依赖包,注意spring-websocket.jar包版本必须与spring.jar一致

本教程使用4.0.2版本,可前往spring-4.0.2所有框架包下载。

三. 配置spring-mvc.xml文件

3.1、在根节点beans加入WebSocket:
添加xml名字空间websocket,并指定该名字空间对应的验证文件(7、15、16行)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="
                  http://www.springframework.org/schema/beans
                  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                  http://www.springframework.org/schema/context  
                  http://www.springframework.org/schema/context/spring-context-4.0.xsd
                  http://www.springframework.org/schema/mvc  
                  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
			      http://www.springframework.org/schema/websocket
			      http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">

3.2、配置WebSocket处理器与拦截器:

<!-- 配置WebSocket处理器 -->
<bean id="websocket" class="com.cn.socket.FaceWebSocketHander" />
<!-- 配置WebSocket拦截器 -->
<websocket:handlers>
    <!-- 跟前端请求的url相关 -->
    <websocket:mapping path="/socket/face" handler="websocket" />  
    <websocket:handshake-interceptors>
        <bean class="com.cn.socket.frame.HandshakeInterceptor" />
    </websocket:handshake-interceptors>
</websocket:handlers>

四. WebSocket处理器

package com.cn.socket;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * WebSocket处理器
 */
public class FaceWebSocketHander implements WebSocketHandler {
	
	private static Logger log = Logger.getLogger("face");
	// 保存所有的用户session
	private static final Map<String, WebSocketSession> clients = new HashMap<String, WebSocketSession>();
	// 会话流水号,long型。自加一增加。
	private static long ccId = 1;
    
    /**
     *  连接就绪时
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    	log.info("新连接:"+session.getId());
    	// 保存到session中
 	    clients.put(sessionId, webSocketSession);
    }
    
    /**
     * 处理信息
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> webSocketMessage) throws Exception {
    	String sessionId = session.getId();
    	log.info("\n【来自客户端sessionId["+sessionId+"]的消息】:\n"+webSocketMessage.getPayload().toString());
 	    // 发送一条信息到前端
 	    session.sendMessage("发送一条消息到客户端");
    }
    
    /**
     * 处理传输时异常
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
        log.error("处理传输时异常:"+throwable);
    }
    
    /**
     * 关闭连接时
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    	log.info("关闭连接:"+session.getId());
    }
    
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public static synchronized long getCcId() {
    	FaceWebSocketHander.ccId++;
    	return FaceWebSocketHander.ccId;
    }

    public static synchronized Map<String, WebSocketSession> getClients() {
    	return clients;
    }
}

五. WebSocket拦截器

package com.cn.socket.frame;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * WebSocket握手拦截器
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

	private static Logger log = Logger.getLogger("face");
	
    /**
     * 握手前
     */
	@Override
    public boolean beforeHandshake(
            ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
            Map<String, Object> attributes) throws Exception {
        return super.beforeHandshake( request, response, wsHandler, attributes );
    }

    /**
     * 握手后
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        super.afterHandshake(request, response, wsHandler, ex);
    }
}

目前为止,服务端已经配置完成!

六. 客户端

6.1、首先引入Sockjs插件:

<!-- 加载Sockjs -->
<script src="https://cdn.bootcss.com/sockjs-client/1.4.0/sockjs.min.js"></script>

6.2、初始化Socket:

// 服务端WebSocket的访问路径(3.2、配置WebSocket处理器与拦截器)。(注意:路径前缀务必添加websocket的“ws://”)
varaction = 'ws://localhost/socket/face';
// socket
var websocket;
// 初始化Socket
if('WebSocket' in window) {
	websocket = new WebSocket(action);  
} else if('MozWebSocket' in window) {
	websocket = new MozWebSocket(action);
} else {
	websocket = new SockJS(action);
}

// 连接成功建立的回调方法  
websocket.onopen = function () {
    layer.msg('WebSocket连接成功!');
}
// 接收服务器推送信息
websocket.onmessage = function (event) {
      	//获取返回数据
      	var json = JSON.parse(event.data);
});

// 发送消息到服务器
websocket.send(JSON.stringify({
  	type: 'chatMessage' // 随便定义,用于在服务端区分消息类型
  	,data: msg  // 可以定义msg对象
}));

大功告成!

七. 完整版案例

网页版仿QQ实现在线聊天功能完整案例(附带源码)



https://www.xamrdz.com/backend/3gr1960630.html

相关文章: