bl双性强迫侵犯h_国产在线观看人成激情视频_蜜芽188_被诱拐的少孩全彩啪啪漫画

java實現websocket的兩種方式實例詳解-創新互聯

一、介紹

1.兩種方式,一種使用tomcat的websocket實現,一種使用spring的websocket

創新互聯長期為1000+客戶提供的網站建設服務,團隊從業經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯網生態環境。為淮上企業提供專業的成都網站建設、網站設計淮上網站改版等技術服務。擁有十年豐富建站經驗和眾多成功案例,為您定制開發。

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; 
 } 
} 

網站題目:java實現websocket的兩種方式實例詳解-創新互聯
本文來源:http://vcdvsql.cn/article24/cedgce.html

成都網站建設公司_創新互聯,為您提供網站內鏈小程序開發微信公眾號網站策劃品牌網站建設做網站

廣告

聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯

h5響應式網站建設