天天看點

WebSocket

一、服務端

package com.feng.web;

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

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

/**
 * @ServerEndpoint注解是一個類層次的注解,它的功能主要是将目前的類定義成一個websocket伺服器端
 * @author fengzp
 *
 */
@ServerEndpoint(value = "/websocket")
public class WebSocketSession{
    
    private static int onlineCount = 0;
    
    /**
     * 用來記錄每一連接配接的線程安全集合
     */
    private static CopyOnWriteArraySet<WebSocketSession> webSocketSessionSet = new CopyOnWriteArraySet<WebSocketSession>();
    
    private Session session;
    
    /**
     * 成功建立連接配接時調用
     * @param session
     */
    @OnOpen
    public void come(Session session){
        this.session = session;
        webSocketSessionSet.add(this);
        WebSocketSession.addCount();
        System.out.println("進來了, 目前人數:"+WebSocketSession.getCount());
    }
    
    /**
     * 連接配接斷開時調用
     */
    @OnClose
    public void leave(){
        webSocketSessionSet.remove(this);
        WebSocketSession.subCount();
        System.out.println("離開了, 目前人數:"+WebSocketSession.getCount());
    }
    
    /**
     * 收到資訊時調用
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("資訊來了:"+message);
        for(WebSocketSession s : webSocketSessionSet){
            try {
                s.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
    
    /**
     * 發生錯誤時調用
     * @param session
     * @param error
     */
    @OnError
    public void error(Session session, Throwable error){
        System.out.println("發送錯誤了");
        error.printStackTrace();
    }
    
    public void sendMessage(String msg) throws IOException{
        this.session.getBasicRemote().sendText(msg);
    }
    
    public static synchronized void addCount(){
        WebSocketSession.onlineCount++;
    }
    
    public static synchronized void subCount(){
        WebSocketSession.onlineCount--;
    }
    
    public static int getCount(){
        return WebSocketSession.onlineCount;
    }
}      

二、用戶端

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-2.2.3.js"></script>
<script type="text/javascript">
    var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8080/JavaWebSocket/websocket");
    }else{
        alert("目前浏覽器不支援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();
     }
     
        function send(){
            var text = $("#text").val();
            websocket.send(text); 
        }
        
       function setMessageInnerHTML(html){
        $("#message").html($("#message").html()+html+'<br/>');
    }
</script>
<title>Insert title here</title>
</head>
<body>
    <input id="text" type="text"/><br/>
    <button onclick="send()">發送</button>
    <button onclick="closeWebSocket()">關閉</button>
    <div id="message"></div>
</body>
</html>      

三、模拟多用戶端進行測試

WebSocket