websocket的通信形式今天刚学,好处就不说了,网上有很多,下面把写的即时通信的demo记录下来,运行出来像下面一样:
一、spring必须4.0以上,maven的pom文件如下:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>4.2.4.RELEASE</version> </dependency>
当然了,还有servlet等等了。。。那些就自己查了
二、spring中,关于websocket的配置:
<bean id="websocket" class="com.wang.test.websocket.demo.WebSocketHander" /> <websocket:handlers> <websocket:mapping path="/echo" handler="websocket" /> <websocket:handshake-interceptors> <bean class="com.wang.test.websocket.demo.HandshakeInterceptor" /> </websocket:handshake-interceptors> </websocket:handlers>
不要忘记引入xsd文件,
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd
整个关于websocket的配置文件如下:
<?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: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/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd"> <bean id="websocket" class="com.wang.test.websocket.demo.WebSocketHander" /> <websocket:handlers> <websocket:mapping path="/echo" handler="websocket" /> <websocket:handshake-interceptors> <bean class="com.wang.test.websocket.demo.HandshakeInterceptor" /> </websocket:handshake-interceptors> </websocket:handlers> </beans>
三、Interceptor类
package com.wang.test.websocket.demo; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.socket.WebSocketHandler; import javax.servlet.http.HttpServletRequest; import java.util.Map; public class HandshakeInterceptor implements org.springframework.web.socket.server.HandshakeInterceptor{ // 初次握手访问前 @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception { if (request instanceof ServletServerHttpRequest) { HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); String userName = "xq"; // 使用userName区分WebSocketHandler,以便定向发送消息 // String userName = (String) // session.getAttribute("WEBSOCKET_USERNAME"); map.put("WEBSOCKET_USERNAME", userName); servletRequest.getSession().setAttribute("WEBSOCKET_USERNAME", userName); } return true; } // 初次握手访问后 @Override public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) { } }
四、WebSocketHander类
package com.wang.test.websocket.demo; import org.apache.log4j.Logger; import org.springframework.web.socket.*; import java.io.IOException; import java.util.ArrayList; public class WebSocketHander implements WebSocketHandler { private static final Logger logger = Logger.getLogger(WebSocketHander.class); private static final ArrayList<WebSocketSession> users = new ArrayList<>(); // 初次链接成功执行 @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.debug("链接成功......"); users.add(session); String userName = (String) session.getAttributes().get("WEBSOCKET_USERNAME"); if (userName != null) { // 查询未读消息 int count = 5; session.sendMessage(new TextMessage(count + "")); } } // 接受消息处理消息 @Override public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception { sendMessageToUsers(new TextMessage(webSocketMessage.getPayload() + "")); } @Override public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception { if (webSocketSession.isOpen()) { webSocketSession.close(); } logger.debug("链接出错,关闭链接......"); users.remove(webSocketSession); } @Override public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception { logger.debug("链接关闭......" + closeStatus.toString()); users.remove(webSocketSession); } @Override public boolean supportsPartialMessages() { return false; } /** * 给所有在线用户发送消息 * * @param message */ public void sendMessageToUsers(TextMessage message) { for (WebSocketSession user : users) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } /** * 给某个用户发送消息 * * @param userName * @param message */ public void sendMessageToUser(String userName, TextMessage message) { for (WebSocketSession user : users) { if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } break; } } } }
五、页面显示文件:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script> <!-- 新 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- 可选的Bootstrap主题文件(一般不用引入) --> <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!-- jQuery文件。务必在bootstrap.min.js 之前引入 --> <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <title>webSocket测试</title> <script type="text/javascript"> $(function() { var websocket; if ('WebSocket' in window) { alert("WebSocket"); var url = 'ws://' + window.location.host + '/SSMTest/echo'; websocket = new WebSocket(url); //websocket = new WebSocket("ws://127.0.0.1:8080/SSMTest/echo"); } else if ('MozWebSocket' in window) { alert("MozWebSocket"); websocket = new MozWebSocket("ws://echo"); } else { alert("SockJS"); websocket = new SockJS("http://127.0.0.1:8080/SSMTest/sockjs/echo"); } websocket.onopen = function(evnt) { $("#tou").html("链接服务器成功!") }; websocket.onmessage = function(evnt) { $("#msg").html($("#msg").html() + "<br/>" + evnt.data); }; websocket.onerror = function(evnt) { }; websocket.onclose = function(evnt) { $("#tou").html("与服务器断开了链接!") } $('#send').bind('click', function() { send(); }); function send() { if (websocket != null) { var message = document.getElementById('message').value; websocket.send(message); } else { alert('未与服务器链接.'); } } }); </script> </head> <body> <div class="page-header" id="tou">webSocket及时聊天Demo程序</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> <!-- /input-group --> </div> <!-- /.col-lg-6 --> </div> <!-- /.row --> </body> </html>
六、参考:http://blog.csdn.net/mr_zhuqiang/article/details/46618197 把这里面配置形式改了
七、代码地址:https://github.com/hejiawang/SSMTest