websocket(二) websocket的簡單實現,識別用戶屬性的群聊


沒什么好說的,websocket實現非常簡單,我們直接看代碼。
運行環境:jdk8 tomcat8   無須其他jar包。   具體環境支持自己百度





package com.reach.socketController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value ="/newwebsocket/{userId}")
public class Webcomment {
    @Resource
    private Webcomment webcomment;
    
    //靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
    private static int onlineCount = 0;
    //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通信的話,可以使用Map來存放,其中Key可以為用戶標識
    private static CopyOnWriteArraySet<Webcomment> webSocketSet = new CopyOnWriteArraySet<Webcomment>();  
  //線程安全的Map private static ConcurrentHashMap<String,Session> webSocketMap = new ConcurrentHashMap<String,Session>();
//建立連接的方法 @OnOpen public void onOpen(Session session,@PathParam("userId")String userId){ /*獲取從/websocket開始的整條鏈接,用於獲取userId?***=***的參數 String uri = session.getRequestURI().toString();*/ webSocketMap.put(userId, session); addOnlineCount(); //在線數加 System.out.println(userId+"進入聊天室"); System.out.println("有新連接加入!當前在線人數為" + getOnlineCount()); } /** * 連接關閉調用的方法 */ @OnClose public void onClose(Session session){ Map<String, String> map = session.getPathParameters(); webSocketMap.remove(map.get("userId")); //從set中刪除 for(String user:webSocketMap.keySet()){ System.out.println(user); } subOnlineCount(); //在線數減 System.out.println("有一連接關閉!當前在線人數為" + getOnlineCount()); } /** * 收到客戶端消息后調用的方法 * @param message 客戶端發送過來的消息 * @param session 可選的參數 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("來自客戶端的消息:" + message); //獲取用戶ID Map<String, String> map = session.getPathParameters(); String userId = map.get("userId"); for(String user:webSocketMap.keySet()){ try { sendMessage(user+"你好,我是"+userId+" "+message,webSocketMap.get(user)); } catch (IOException e) { e.printStackTrace(); } } } /** * 發生錯誤時調用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error){ System.out.println("發生錯誤"); error.printStackTrace(); } public void sendMessage(String message,Session session) throws IOException{ if(session.isOpen()){ session.getAsyncRemote().sendText(message);
 } //this.session.getAsyncRemote().sendText(message);
 } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { Webcomment.onlineCount++; } public static synchronized void subOnlineCount() { Webcomment.onlineCount--; } }

 

html代碼,可以單獨建立html,無須放在項目中

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
  <meta name="generator" content="editplus" />
  <meta name="author" content="" />
  <meta name="keywords" content="" />
  <meta name="description" content="" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script src="jquery-1.8.3.min.js" type="text/javascript"></script>
 </head>

 <body>


  <center>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">發送消息</button>
<hr/>
<button onclick="closeWebSocket()">關閉WebSocket連接</button>
<hr/>
<div id="message"></div>




 </body>
 <script type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
alert('當前瀏覽器支持 websocket');
websocket = new WebSocket("ws://localhost:8080/Y-websocket/newwebsocket/234");
}
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();
}
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
//發送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>

 

 

友情提示: 向客戶端發送信息  sendText()是用來傳輸字符串的,有一個sendObject()方法可以通過轉碼器發送javabean。  

       但是這里我們不推薦,因為非常麻煩。最簡單的辦法,就是把要發送的bean轉成json字符串。 bean轉json

       然后在頁面將接收的json字符串轉成json:JSON.parse(event.data)

 當你看完這兩篇文章,雖然不保證websocket理解透徹,但是結合業務來使用websocket已經不是難題了!websocket學習起來就是這么簡單


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM