Creating two separate websocket connections for send and receive on localhost

StackOverflow https://stackoverflow.com/questions/23214896

  •  07-07-2023
  •  | 
  •  

سؤال

I am new to websockets.

It is expected to send data(any data) on the send websocket connection using some port(ex:8000) and the localhost should echo the same data to the browser using a different websocket connection through a different port(ex:9000).

I understand websocket supports full duplex communication on a single connection,but the above is the design to implement.

Question 1) Is the above design possible? Question 2) If yes,how to create two websocket connections(one to send and one to receive) to a single localhost websocket server?

هل كانت مفيدة؟

المحلول

1) Yes.

2) Creating two separated websockets. They will be different objects though.

You could blend both objects in a composite object like this:

var compositeWebSocket = function(urlSend, urlReceive){
    var me = {};
    var wsSend = new WebSocket(urlSend);
    var wsReceive = new WebSocket(urlReceive);
    var open = 0;

    wsSend.onopen = opening;
    wsReceive.onopen = opening;

    var opening = function(){
        if(open == 2){
            if(me.onopen)
                me.onopen();
        }
        else
            open++;
    };

    var closing = funcion(){
        try{wsSend.close();}catch(){}
        try{wsReceive.close();}catch(){}
        if(me.onclose)
            me.onclose();
    }

    me.send = wsSend.send;

    wsReceive.onmessage = function(msg){
        if(me.onmessage)
            me.onmessage(msg);
    }

    return me;
}

(Whatch out, this code is not tested and it is just an idea)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top