複数のWebsocketを1ページにマージし、Typeに従って異なるタイプのメッセージを送受信する
Websocketのマージにより、ページの複数のwebssocket接続の問題を解決
背景
1.トップページを開くと、複数のwebsocket接続が開始され、各バックエンドのそれぞれのwebsocketが呼び出されます.2.他のサブページはホームページにネストされており、サブページを開くとサブページのwebsocket接続が開始されます.3.フロントエンドとバックエンド:1ページ内の複数のwebsocketと他のサブページのwebsocketを1つに統合したい.
一.フロントエンドページのマージトップページにwebsoclet接続を作成し、異なるwebsocket接続は異なるtypeを設定し、onopenメソッドで複数の異なるwebsocketに代わって異なるタイプのメッセージを送信する効果を複数回send(type)する.
二.バックエンドマージ複数のwebsocket
>フロントエンドパスのtype,onopen,onmessageメソッドで異なるメソッドを実行
考え方は大体このようにして,複数のwebsocketをカプセル化しtypeに基づいて動的に対応する方法を実行する.
背景
1.トップページを開くと、複数のwebsocket接続が開始され、各バックエンドのそれぞれのwebsocketが呼び出されます.2.他のサブページはホームページにネストされており、サブページを開くとサブページのwebsocket接続が開始されます.3.フロントエンドとバックエンド:1ページ内の複数のwebsocketと他のサブページのwebsocketを1つに統合したい.
一.フロントエンドページのマージ
var mysocket = null;
function createWebsocket(){
var webUrl = window.location.host;
if('WebSocket' in window){
if(mysocket==null){
mysocket = new WebSocket("ws://${xxx}/xxx?type="+type);
mysocket.onopen = function(){
// websocket type
myscoket.send("type");
mysocket.send("type1");
}
mysocket.onmessage = function(msg){
// type
var type = ($.paiseJSON(msg.data)).type;
if(type==xxx){
xxx;
}
if(type==xxx1){
xxx;
}
}
mysocket.onclose = function(){
alert(" ")
}
mysocket.onbeforeunload = function(){
mysocket.close();
}
}else{
$.message.show({
title:' ',
msg:' , '
});
}
}
二.バックエンドマージ複数のwebsocket
>フロントエンドパスのtype,onopen,onmessageメソッドで異なるメソッドを実行
@ServerEndpoint(value="/xxx/{param}",configurator = GetHttpSessionConfigurator.class)
public class MyWebSocketServlet{
private static final long serivalVersionUID = xxx;
@OnOpen//
public void open(Session session,EdpointConfig config,@PathParam("param")String param){
try{
param = (String)config.getUserProperties().get("type");
}catch(Exception e){
e.printStackTrace();
}
// type ,
if(param.equals("xxx")){
HttpSession httpSession = (HttpSession)config.getUserPropertie().get(HttpSession.class.getName());
AuthUser user = (AuthUser)httpSession.getAttribute(Constans.LOGIN_USER);
MessageCenter.getInstance().addUserSession(session,user.getUsername());
}
if(param.equals("xxx1")){
xxx;
}
}
@OnMessage//
public void handlerMessage(String message,Sesion session){
// startWith message ,
if(message.startWith("xxx")){
xxx;
}
}
@OnClose//
public void onClose() {
sessions.remove(this);
}
@OnError
public void onError(Session session, Throwable error) {
log.error(" ");
error.printStackTrace();
}
}
考え方は大体このようにして,複数のwebsocketをカプセル化しtypeに基づいて動的に対応する方法を実行する.