js+java websocket記錄

首先websocket後臺需要在web服務器運行,所以先搭建一個web項目。websocket需要依賴其他的jar包,引入依賴

<dependency>
  <groupId>javax</groupId>
  <artifactId>javaee-api</artifactId>
  <version>7.0</version>
  <scope>provided</scope>
</dependency>

新建一個類,該類建立一個服務端點 ServerEndpoint

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Rice
 * @create 2020/06/24 15:56
 */
@ServerEndpoint("/ws/{sid}")
public class WSServer {

    private Session session ;
    private static ConcurrentHashMap<String,Session> ss = new ConcurrentHashMap<String,Session>();
    private int oln ;

    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid){
        oln++;
        this.session = session;
        ss.put(sid,session);
    }

    @OnMessage
    public void onMessage(String message ,Session session,@PathParam("sid") String sid ) throws IOException {
        Msg msg = Msg.getInstance(message);
        msg.setUser(sid);
        if(msg.getTid()==1){
            privateChat(msg);
            return ;
        }

    }

    @OnClose
    public void onClose(@PathParam("sid") String sid){
        oln--;
        ss.remove(sid);
    }

    @OnError
    public void onError(Session session ,Throwable error){
        System.out.println(error);
    }


    private void privateChat(Msg msg) throws IOException {
        if (ss.containsKey(msg.getTsid())){
            Session ts = ss.get(msg.getTsid());
            ts.getBasicRemote().sendText(Msg.forwordMSg(msg));
        }else{
            this.session.getBasicRemote().sendText("對方不在線");
        }
    }

}

前端(客戶端點):

ws = new WebSocket("ws://localhost:8080/wws/ws/"+_this.luser)
                            ws.onmessage=function(event){
                                let rm = JSON.parse(event.data);
                                if(!_this.msgs[rm.user]){
                                    _this.$set(_this.msgs,rm.user,new Array());
                                }
                                _this.msgs[rm.user].push(rm.user+": "+rm.msg);
                            }

當客戶端點調用new Websocket時,會發起和服務端的連接。當websocekt的readystate變爲1時,會觸發後端onopen事件,此時一般會將建立連接的session加入到管理的Map中,記錄session的名字和session.以此方便進行消息的轉發。

當客戶端readystate=1(連接成功),客戶端可以進行發消息,關閉連接。當客戶端調用websocket.send(String msg),後臺會觸發onMessage方法並且把消息以及發消息的session傳入到該方法中進行處理。通常客戶端發送的消息需要自行規定數據報格式,如JSON,給後臺進行解析。

客戶端點同樣的需要進行onmessage方法的處理,當服務端往客戶端session發送消息,同樣會觸發客戶端的onmessage方法。以此達到即時溝通

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章