1. 程式人生 > >spring boot + webSocket 實現簡單會話與線上人數統計的demo

spring boot + webSocket 實現簡單會話與線上人數統計的demo

webSocket推送是常用於生產專案的模組,在我們部門做的一個彙報演示的demo中遇到了webSocket的一些問題。

自己下來看看了看webSocket的東西,結合spring boot 做了一個簡單的demo;

介紹的部分大家可以參考眾多的帖子,度娘

http://www.cnblogs.com/wei2yi/archive/2011/03/23/1992830.html

http://my.oschina.net/ldl123292/blog/304360

好的,現在貼一下我的程式碼 註釋寫的很細,也很簡單,一下就能看懂。

java:

package com.haungteng.springboot.controller.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author ht
 * @describle 統計線上人數的demo
 */

@Component
@ServerEndpoint("/websocket")  //該註解表示該類被宣告為一個webSocket終端
public class MySocket {
    //初始線上人數
    private static int online_num = 0;
    //執行緒安全的socket集合
    private static CopyOnWriteArraySet<MySocket> webSocketSet = new CopyOnWriteArraySet<MySocket>();
    //會話
    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        System.out.println("有連結加入,當前人數為:"+getOnline_num());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有連結關閉,當前人數為:"+getOnline_num());
    }

    @OnMessage
    public void onMessage(String message,Session session) throws IOException{
        System.out.println("來自客戶端的訊息:"+message);
        for(MySocket item:webSocketSet){
            this.session.getAsyncRemote().sendText("hello");
        }
    }
    public synchronized int getOnline_num(){
        return MySocket.online_num;
    }
    public synchronized int subOnlineCount(){
        return MySocket.online_num--;
    }
    public synchronized int addOnlineCount(){
        return MySocket.online_num++;
    }
}
html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My WebSocket</title>
</head>
<body>
    <h2 onclick="openTanTan()" style="color:dodgerblue;text-align: center">WeTanTan</h2>
    <div id="tantanbox" style=
"width:800px;height:498px;margin:0 auto;"> <div id="box-left" style="float:left;width:600px;height:500px;"> <div id="content" style="height:350px;border:1px solid dodgerblue;"></div> <div id="input-content" style="height:145px;border:1px solid dodgerblue
;"><textarea id="input-message" style="width:99%;height:96%"></textarea></div> <button id="btn1" onclick="sendMessage()" style="width:38px;height:18px;line-height:18px;border:0;margin:4px 0 0 10px;">send</button> <button id="btn2" onclick="ClosedWebSocket()" style="width:38px;height:18px;line-height:18px;border:0;margin:4px 0 0 10px;">close</button> </div> <div id="box-right" style="float:left;width:195px;height:497px;border:1px solid dodgerblue"> <span style="font-size:10px;color:dodgerblue;font-weight:bold;">線上人數:</span> <hr/> <div id="count-users" style="font-size:10px;color:dodgerblue;font-weight:bold"></div> </div> </div> </body> <script> var usernames=[]; var username=""; window.onload = function(){ document.getElementById("tantanbox").style.display='none'; }; function openTanTan(){ alert("open your WeTanTan chat!"); username = window.prompt("輸入你的名字:"); //document.write("welcome to wetantan!<p id='username'>"+username+"</p>"); usernames.push(username); document.getElementById("tantanbox").style.display='block'; /*--------------------開始websocket部分----------- ---------*/ var ws = null;//申請一個websocket物件 //判斷當前瀏覽器是不是支援websocket if('window' in window){ startWebSocket(); }else{ alert("NO SUPPORT!"); return; } }; function startWebSocket() { ws = new WebSocket("ws://localhost:8080/websocket"); document.getElementById("count-users").innerHTML=""; ws.onclose = function () { sendInnerHtml("<span style='font-size: 20px;color:greenyellow;font-weight: bold'>"+"Bye~~"+"</span>"); }; ws.onerror = function () { sendInnerHtml("websocket error"); }; ws.onopen = function (event) { sendInnerHtml("Welcome to WeTanTan Light social web! "+"<span style='font-size: 30px;font-weight: bold;color:orange'>"+username+"</span>"); }; ws.onmessage = function (e) { console.log(e) document.getElementById("count-users").innerHTML=e.data+""; sendInnerHtml('<br/>'+"伺服器"+":"+e.data); }; //監聽方法,監聽websocket關閉 window.onbeforeunload = function(){ ws.close(); }; } function sendInnerHtml(innerHtml){ document.getElementById("content").innerHTML+=innerHtml+'<br/>'; }; function ClosedWebSocket(){ ws.close(); setTimeout(function(){ document.getElementById("tantanbox").style.display='none'; },1000); }; function sendMessage() { var message = document.getElementById("input-message").value; ws.send(message); document.getElementById("content").innerHTML='<br/>'+username+":"+message; document.getElementById("input-message").value=""; }; </script> </html>