java websocket實現即時聊天系統

即時聊天系統

後臺代碼

package com.wyn.pro.wynpro.customermanager.test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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.PathParam;
import javax.websocket.server.ServerEndpoint;

import net.sf.json.JSONObject;

@ServerEndpoint("/hello/{username}")
public class WebsocketTest {
    private Session session;
    private String username;

    //靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。  
    private static int onlineCount = 0;

    private static final CopyOnWriteArraySet<WebsocketTest> webSocketSet=new CopyOnWriteArraySet<WebsocketTest>();

    // 日期格式化  
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");


    public WebsocketTest(){
        System.out.println("WebsocketTest..");
    }

    @OnOpen
    public void onopen(Session session,@PathParam("username") String username){
        System.out.println("連接成功");
        this.session=session;
        this.username=username;
        webSocketSet.add(this);
        addOnlineCount();
        System.out.println(onlineCount);
    }

    /**  
     * 接受客戶端的消息,並把消息發送給所有連接的會話  
     * @param message 客戶端發來的消息  
     * @param session 客戶端的會話  
     */    
    @OnMessage      
    public void onsend(Session session,String msg){
        try {
            JSONObject fObject = JSONObject.fromObject(msg);
            fObject.put("date", DATE_FORMAT.format(new Date()));
            for(WebsocketTest websocketTest:webSocketSet) {
                synchronized (WebsocketTest.class) { 
                    fObject.put("isSelf", websocketTest.session.equals(session));
                    fObject.put("username", this.username);
                    fObject.put("num", onlineCount);
                    //websocketTest.session.getAsyncRemote().sendText(fObject.toString());
                    websocketTest.sendMessage(fObject.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onclose(Session session){
        // 添加關閉會話時的操作  
        webSocketSet.remove(this);  //從set中刪除  
        subOnlineCount();           //在線數減1  
        System.out.println("close....");
    }

    @OnError   
    public void error(Throwable t) {    
        // 添加處理錯誤的操作    
        System.out.println("發生錯誤了");  
    }  

    public  static synchronized void addOnlineCount() {
        WebsocketTest.onlineCount++;
    }

    public static synchronized void subOnlineCount() {  
        WebsocketTest.onlineCount--;  
    }  

    public synchronized  void  sendMessage(String message) throws IOException{  
        this.session.getAsyncRemote().sendText(message);//非阻塞式的  
    }  

}

前臺頁面代碼

<%@ 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">
<title>即時聊天系統</title>
</head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    var websocket;

    function linksys(){
        //debugger
        if(websocket){
            alert("已經建立連接");
            return;
        }
        var username = $("#name").val();
        if(username==null||username==""){
            alert("請先輸入代號");
            return;
        }
        websocket = new WebSocket("ws://192.168.0.17:9999/order/hello/"+username);
        /*與後臺系統建立連接  */
        websocket.onopen = function(evn){
            console.log("與後臺系統建立連接---------當前連接數:");
        }

        websocket.onmessage = function(evn){
            debugger
            message = JSON.parse(evn.data);
            $("#num").text(message.num);
            //alert(message.username);
            $("#table").append("<tr><td>"+message.username+"</td><td>"+message.date+"</td></tr><tr><td colspan='2'>"+message.content+"</td></tr>");
        } 

        websocket.onclose = function(){
                console.log("關閉");
         };
    }

    function subsend(){
        if(websocket){
            content1 = $("#content").val();
            jsonstr=JSON.stringify({  
                content : content1 
            });
            //alert(jsonstr);
            websocket.send(jsonstr);
        }else{
            alert("請先連接,再發送信息");
        }
    }

</script>
<body>
<h1>即時聊天系統</h1>
當前用戶姓名<input type="text" name="username" id="name"><button onclick="linksys()">連接系統</button><br>
聊天內容<input type="text" name="content" id="content"><button onclick="subsend()" >發送</button><br>
當前在線客戶<p id="num"><p>
---------------------------------------------------------------<br>
聊天記錄<br>
<table id="table" border="1">
</table>
</body>
</html>

maven依賴

<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.8.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
    <dependency>
        <groupId>net.sf.ezmorph</groupId>
        <artifactId>ezmorph</artifactId>
        <version>1.0.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api -->
    <dependency>
        <groupId>javax.websocket</groupId>
        <artifactId>javax.websocket-api</artifactId>
        <version>1.0</version>
        <scope>provided</scope>
    </dependency>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章