最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java 實(shí)現(xiàn)websocket的兩種方式實(shí)例詳解

 更新時(shí)間:2018年07月27日 15:25:59   作者:Mia_li  
這篇文章主要介紹了java 實(shí)現(xiàn)websocket的兩種方式實(shí)例詳解,一種使用tomcat的websocket實(shí)現(xiàn),一種使用spring的websocket,本文通過代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下

一、介紹

1.兩種方式,一種使用tomcat的websocket實(shí)現(xiàn),一種使用spring的websocket

2.tomcat的方式需要tomcat 7.x,JEE7的支持。

3.spring與websocket整合需要spring 4.x,并且使用了socketjs,對不支持websocket的瀏覽器可以模擬websocket使用

二、方式一:tomcat

使用這種方式無需別的任何配置,只需服務(wù)端一個(gè)處理類,

 服務(wù)器端代碼

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("給一個(gè)人", 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"); 
//判斷當(dāng)前瀏覽器是否支持WebSocket 
if ('WebSocket' in window) { 
 websocket = new WebSocket("ws://" + document.location.host + "/WebChat/websocket/" + username + "/"+ _img); 
} else { 
 alert('當(dāng)前瀏覽器 Not support websocket') 
} 
//連接發(fā)生錯(cuò)誤的回調(diào)方法 
websocket.onerror = function() { 
 setMessageInnerHTML("WebSocket連接發(fā)生錯(cuò)誤"); 
}; 
//連接成功建立的回調(diào)方法 
websocket.onopen = function() { 
 setMessageInnerHTML("WebSocket連接成功"); 
} 
//接收到消息的回調(diào)方法 
websocket.onmessage = function(event) { 
 setMessageInnerHTML(event.data); 
} 
//連接關(guān)閉的回調(diào)方法 
websocket.onclose = function() { 
 setMessageInnerHTML("WebSocket連接關(guān)閉"); 
} 
//監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會(huì)拋異常。 
window.onbeforeunload = function() { 
 closeWebSocket(); 
} 
//關(guān)閉WebSocket連接 
function closeWebSocket() { 
 websocket.close(); 
} 

發(fā)送消息只需要使用websocket.send(“發(fā)送消息”),就可以觸發(fā)服務(wù)端的onMessage()方法,當(dāng)連接時(shí),觸發(fā)服務(wù)器端onOpen()方法,此時(shí)也可以調(diào)用發(fā)送消息的方法去發(fā)送消息。關(guān)閉websocket時(shí),觸發(fā)服務(wù)器端onclose()方法,此時(shí)也可以發(fā)送消息,但是不能發(fā)送給自己,因?yàn)樽约旱囊呀?jīng)關(guān)閉了連接,但是可以發(fā)送給其他人。

三、方法二:spring整合

WebSocketConfig.java

這個(gè)類是配置類,所以需要在spring mvc配置文件中加入對這個(gè)類的掃描,第一個(gè)addHandler是對正常連接的配置,第二個(gè)是如果瀏覽器不支持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

這個(gè)類的作用就是在連接成功前和成功后增加一些額外的功能,Constants.java類是一個(gè)工具類,兩個(gè)常量。

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區(qū)分WebSocketHandler,以便定向發(fā)送消息 String userName = 
   * (String) session.getAttribute(Constants.SESSION_USERNAME); if 
   * (userName==null) { userName="default-system"; } 
   * attributes.put(Constants.WEBSOCKET_USERNAME,userName); 
   * 
   * } } 
   */ 
  //使用userName區(qū)分WebSocketHandler,以便定向發(fā)送消息(使用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

這個(gè)類是對消息的一些處理,比如是發(fā)給一個(gè)人,還是發(fā)給所有人,并且前端連接時(shí)觸發(fā)的一些動(dòng)作

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;// 這個(gè)會(huì)出現(xiàn)性能問題,最好用Map來存儲(chǔ),key用userid 
 private static Logger logger = Logger.getLogger(ChatMessageHandler.class); 
 static { 
  users = new ArrayList<WebSocketSession>(); 
 } 
 /** 
  * 連接成功時(shí)候,會(huì)觸發(fā)UI上onopen方法 
  */ 
 @Override 
 public void afterConnectionEstablished(WebSocketSession session) throws Exception { 
  System.out.println("connect to the websocket success......"); 
  users.add(session); 
  // 這塊會(huì)實(shí)現(xiàn)自己業(yè)務(wù),比如,當(dāng)用戶登錄后,會(huì)把離線消息推送給用戶 
  // TextMessage returnMessage = new TextMessage("你將收到的離線"); 
  // session.sendMessage(returnMessage); 
 } 
 /** 
  * 在UI在用js調(diào)用websocket.send()時(shí)候,會(huì)調(diào)用該方法 
  */ 
 @Override 
 protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { 
  sendMessageToUsers(message); 
  //super.handleTextMessage(session, message); 
 } 
 /** 
  * 給某個(gè)用戶發(fā)送消息 
  * 
  * @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; 
   } 
  } 
 } 
 /** 
  * 給所有在線用戶發(fā)送消息 
  * 
  * @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

正常的配置文件,同時(shí)需要增加對WebSocketConfig.java類的掃描,并且增加

xmlns:websocket="http://www.springframework.org/schema/websocket" 
    http://www.springframework.org/schema/websocket 
    <a target="_blank"  rel="external nofollow" >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(); 
    //調(diào)用后臺(tái)handleTextMessage方法 
    websocket.send(msg); 
   } else { 
    alert("連接失敗!"); 
   } 
  }); 
 </script> 

注意導(dǎo)入socketjs時(shí)要使用地址全稱,并且連接使用的是http而不是websocket的ws

總結(jié)

以上所述是小編給大家介紹的java 實(shí)現(xiàn)websocket的兩種方式實(shí)例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • java 學(xué)習(xí)筆記(入門篇)_java的安裝與配置

    java 學(xué)習(xí)筆記(入門篇)_java的安裝與配置

    學(xué)習(xí)Java已經(jīng)很長時(shí)間了,由于基礎(chǔ)不好遇到問題就無從下手,所以,打算寫Java的隨手筆記來鞏固基礎(chǔ),加強(qiáng)學(xué)習(xí),接下來講解java的安裝,配置等,感興趣的朋友可以參考下
    2013-01-01
  • Java壓縮/解壓文件的實(shí)現(xiàn)代碼

    Java壓縮/解壓文件的實(shí)現(xiàn)代碼

    本文通過實(shí)例代碼給大家分享了Java壓縮/解壓文件的方法,需要的朋友參考下吧
    2017-09-09
  • Spring計(jì)時(shí)器stopwatch使用詳解

    Spring計(jì)時(shí)器stopwatch使用詳解

    這篇文章主要介紹了Spring計(jì)時(shí)器stopwatch使用詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • Maven打包并生成運(yùn)行腳本的示例代碼

    Maven打包并生成運(yùn)行腳本的示例代碼

    這篇文章主要介紹了Maven打包并生成運(yùn)行腳本,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-07-07
  • jdbc連接數(shù)據(jù)庫實(shí)例詳解

    jdbc連接數(shù)據(jù)庫實(shí)例詳解

    在本篇內(nèi)容里小編給大家分享了關(guān)于jdbc如何連接數(shù)據(jù)庫的相關(guān)知識點(diǎn)內(nèi)容,需要的朋友們學(xué)習(xí)下。
    2019-02-02
  • 一起來學(xué)習(xí)Java IO的轉(zhuǎn)化流

    一起來學(xué)習(xí)Java IO的轉(zhuǎn)化流

    這篇文章主要為大家詳細(xì)介紹了Java IO的轉(zhuǎn)化流,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • Java的后臺(tái)文件夾下文件的遍歷完整代碼

    Java的后臺(tái)文件夾下文件的遍歷完整代碼

    這篇文章主要介紹了Java的后臺(tái)文件夾下文件的遍歷完整代碼,首先分享了java中遍歷一個(gè)文件夾里邊的所有文件,然后介紹了用Java遍歷一個(gè)文件夾并獲取它里面的所有內(nèi)容詳細(xì)代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • IDEA代碼規(guī)范插件P3C+代碼注釋模板配置方法

    IDEA代碼規(guī)范插件P3C+代碼注釋模板配置方法

    這篇文章主要介紹了IDEA代碼規(guī)范插件P3C+代碼注釋模板配置方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • Java中final關(guān)鍵字和final的四種用法實(shí)例

    Java中final關(guān)鍵字和final的四種用法實(shí)例

    final關(guān)鍵字代表最終的、不可改變的,下面這篇文章主要給大家介紹了關(guān)于Java中final關(guān)鍵字和final的四種用法實(shí)例,文中通過圖文以及實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-02-02
  • java+Okhttp3調(diào)用接口的實(shí)例

    java+Okhttp3調(diào)用接口的實(shí)例

    這篇文章主要介紹了java+Okhttp3調(diào)用接口的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12

最新評論

龙江县| 厦门市| 遂昌县| 延长县| 新营市| 东港市| 班戈县| 松潘县| 南安市| 监利县| 桐庐县| 赣榆县| 兴隆县| 阆中市| 铁岭县| 德阳市| 秦皇岛市| 都安| 邵东县| 嘉义县| 潞城市| 婺源县| 乌苏市| 罗定市| 阿坝| 开封市| 怀集县| 中卫市| 城市| 佛学| 尚志市| 金门县| 平定县| 普兰店市| 固阳县| 广宗县| 庆城县| 阿瓦提县| 磴口县| 汉源县| 张家港市|