簡單說明
1.兩種方式,一種使用tomcat的websocket實現,一種使用spring的websocket
2.tomcat的方式需要tomcat 7.x,JEE7的支持。
3.spring與websocket整合需要spring 4.x,並且使用了socketjs,對不支持websocket的瀏覽器可以模擬websocket使用
方式一:tomcat
使用這種方式無需別的任何配置,只需服務端一個處理類,
服務器端代碼
- package com.Socket;
- import java.io.IOException;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
- import javax.websocket.*;
- import javax.websocket.server.PathParam;
- import javax.websocket.server.ServerEndpoint;
- import net.sf.json.JSONObject;
- @ServerEndpoint("/websocket/{username}")
- public class WebSocket {
- private static int onlineCount = 0;
- private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
- private Session session;
- private String username;
- @OnOpen
- public void onOpen(@PathParam("username") String username, Session session) throws IOException {
- this.username = username;
- this.session = session;
- addOnlineCount();
- clients.put(username, this);
- System.out.println("已連接");
- }
- @OnClose
- public void onClose() throws IOException {
- clients.remove(username);
- subOnlineCount();
- }
- @OnMessage
- public void onMessage(String message) throws IOException {
- JSONObject jsonTo = JSONObject.fromObject(message);
- if (!jsonTo.get("To").equals("All")){
- sendMessageTo("給一個人", jsonTo.get("To").toString());
- }else{
- sendMessageAll("給所有人");
- }
- }
- @OnError
- public void onError(Session session, Throwable error) {
- error.printStackTrace();
- }
- public void sendMessageTo(String message, String To) throws IOException {
- // session.getBasicRemote().sendText(message);
- //session.getAsyncRemote().sendText(message);
- for (WebSocket item : clients.values()) {
- if (item.username.equals(To) )
- item.session.getAsyncRemote().sendText(message);
- }
- }
- public void sendMessageAll(String message) throws IOException {
- for (WebSocket item : clients.values()) {
- item.session.getAsyncRemote().sendText(message);
- }
- }
- public static synchronized int getOnlineCount() {
- return onlineCount;
- }
- public static synchronized void addOnlineCount() {
- WebSocket.onlineCount++;
- }
- public static synchronized void subOnlineCount() {
- WebSocket.onlineCount--;
- }
- public static synchronized Map<String, WebSocket> getClients() {
- return clients;
- }
- }
客戶端js
- var websocket = null;
- var username = localStorage.getItem("name");
- //判斷當前瀏覽器是否支持WebSocket
- if ('WebSocket' in window) {
- websocket = new WebSocket("ws://" + document.location.host + "/WebChat/websocket/" + username + "/"+ _img);
- } else {
- alert('當前瀏覽器 Not support websocket')
- }
- //連接發生錯誤的回調方法
- websocket.onerror = function() {
- setMessageInnerHTML("WebSocket連接發生錯誤");
- };
- //連接成功建立的回調方法
- websocket.onopen = function() {
- setMessageInnerHTML("WebSocket連接成功");
- }
- //接收到消息的回調方法
- websocket.onmessage = function(event) {
- setMessageInnerHTML(event.data);
- }
- //連接關閉的回調方法
- websocket.onclose = function() {
- setMessageInnerHTML("WebSocket連接關閉");
- }
- //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
- window.onbeforeunload = function() {
- closeWebSocket();
- }
- //關閉WebSocket連接
- function closeWebSocket() {
- websocket.close();
- }
發送消息只需要使用websocket.send("發送消息"),就可以觸發服務端的onMessage()方法,當連接時,觸發服務器端onOpen()方法,此時也可以調用發送消息的方法去發送消息。關閉websocket時,觸發服務器端onclose()方法,此時也可以發送消息,但是不能發送給自己,因為自己的已經關閉了連接,但是可以發送給其他人。
方法二:spring整合
此方式基於spring mvc框架,相關配置可以看我的相關博客文章
WebSocketConfig.java
這個類是配置類,所以需要在spring mvc配置文件中加入對這個類的掃描,第一個addHandler是對正常連接的配置,第二個是如果瀏覽器不支持websocket,使用socketjs模擬websocket的連接。
- package com.websocket;
- 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.config.annotation.WebSocketConfigurer;
- import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
- import org.springframework.web.socket.handler.TextWebSocketHandler;
- @Configuration
- @EnableWebSocket
- public class WebSocketConfig implements WebSocketConfigurer {
- @Override
- public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
- registry.addHandler(chatMessageHandler(),"/webSocketServer").addInterceptors(new ChatHandshakeInterceptor());
- registry.addHandler(chatMessageHandler(), "/sockjs/webSocketServer").addInterceptors(new ChatHandshakeInterceptor()).withSockJS();
- }
- @Bean
- public TextWebSocketHandler chatMessageHandler(){
- return new ChatMessageHandler();
- }
- }
ChatHandshakeInterceptor.java
這個類的作用就是在連接成功前和成功后增加一些額外的功能,Constants.java類是一個工具類,兩個常量。
- package com.websocket;
- import java.util.Map;
- import org.apache.shiro.SecurityUtils;
- 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;
- public class ChatHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
- @Override
- public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
- Map<String, Object> attributes) throws Exception {
- System.out.println("Before Handshake");
- /*
- * if (request instanceof ServletServerHttpRequest) {
- * ServletServerHttpRequest servletRequest = (ServletServerHttpRequest)
- * request; HttpSession session =
- * servletRequest.getServletRequest().getSession(false); if (session !=
- * null) { //使用userName區分WebSocketHandler,以便定向發送消息 String userName =
- * (String) session.getAttribute(Constants.SESSION_USERNAME); if
- * (userName==null) { userName="default-system"; }
- * attributes.put(Constants.WEBSOCKET_USERNAME,userName);
- *
- * } }
- */
- //使用userName區分WebSocketHandler,以便定向發送消息(使用shiro獲取session,或是使用上面的方式)
- String userName = (String) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USERNAME);
- if (userName == null) {
- userName = "default-system";
- }
- attributes.put(Constants.WEBSOCKET_USERNAME, userName);
- return super.beforeHandshake(request, response, wsHandler, attributes);
- }
- @Override
- public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
- Exception ex) {
- System.out.println("After Handshake");
- super.afterHandshake(request, response, wsHandler, ex);
- }
- }
ChatMessageHandler.java
這個類是對消息的一些處理,比如是發給一個人,還是發給所有人,並且前端連接時觸發的一些動作
- package com.websocket;
- import java.io.IOException;
- import java.util.ArrayList;
- import org.apache.log4j.Logger;
- import org.springframework.web.socket.CloseStatus;
- import org.springframework.web.socket.TextMessage;
- import org.springframework.web.socket.WebSocketSession;
- import org.springframework.web.socket.handler.TextWebSocketHandler;
- public class ChatMessageHandler extends TextWebSocketHandler {
- private static final ArrayList<WebSocketSession> users;// 這個會出現性能問題,最好用Map來存儲,key用userid
- private static Logger logger = Logger.getLogger(ChatMessageHandler.class);
- static {
- users = new ArrayList<WebSocketSession>();
- }
- /**
- * 連接成功時候,會觸發UI上onopen方法
- */
- @Override
- public void afterConnectionEstablished(WebSocketSession session) throws Exception {
- System.out.println("connect to the websocket success......");
- users.add(session);
- // 這塊會實現自己業務,比如,當用戶登錄后,會把離線消息推送給用戶
- // TextMessage returnMessage = new TextMessage("你將收到的離線");
- // session.sendMessage(returnMessage);
- }
- /**
- * 在UI在用js調用websocket.send()時候,會調用該方法
- */
- @Override
- protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
- sendMessageToUsers(message);
- //super.handleTextMessage(session, message);
- }
- /**
- * 給某個用戶發送消息
- *
- * @param userName
- * @param message
- */
- public void sendMessageToUser(String userName, TextMessage message) {
- for (WebSocketSession user : users) {
- if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) {
- try {
- if (user.isOpen()) {
- user.sendMessage(message);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- break;
- }
- }
- }
- /**
- * 給所有在線用戶發送消息
- *
- * @param message
- */
- public void sendMessageToUsers(TextMessage message) {
- for (WebSocketSession user : users) {
- try {
- if (user.isOpen()) {
- user.sendMessage(message);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- @Override
- public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
- if (session.isOpen()) {
- session.close();
- }
- logger.debug("websocket connection closed......");
- users.remove(session);
- }
- @Override
- public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
- logger.debug("websocket connection closed......");
- users.remove(session);
- }
- @Override
- public boolean supportsPartialMessages() {
- return false;
- }
- }
spring-mvc.xml
正常的配置文件,同時需要增加對WebSocketConfig.java類的掃描,並且增加
- xmlns:websocket="http://www.springframework.org/schema/websocket"
- http://www.springframework.org/schema/websocket
- <a target="_blank" href="http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd">http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd</a>
客戶端
- <script type="text/javascript"
- src="http://localhost:8080/Bank/js/sockjs-0.3.min.js"></script>
- <script>
- var websocket;
- if ('WebSocket' in window) {
- websocket = new WebSocket("ws://" + document.location.host + "/Bank/webSocketServer");
- } else if ('MozWebSocket' in window) {
- websocket = new MozWebSocket("ws://" + document.location.host + "/Bank/webSocketServer");
- } else {
- websocket = new SockJS("http://" + document.location.host + "/Bank/sockjs/webSocketServer");
- }
- websocket.onopen = function(evnt) {};
- websocket.onmessage = function(evnt) {
- $("#test").html("(<font color='red'>" + evnt.data + "</font>)")
- };
- websocket.onerror = function(evnt) {};
- websocket.onclose = function(evnt) {}
- $('#btn').on('click', function() {
- if (websocket.readyState == websocket.OPEN) {
- var msg = $('#id').val();
- //調用后台handleTextMessage方法
- websocket.send(msg);
- } else {
- alert("連接失敗!");
- }
- });
- </script>
注意導入socketjs時要使用地址全稱,並且連接使用的是http而不是websocket的ws
</div>