简体   繁体   中英

How the websocket bi-directional concept work?

I am using Java Tomcat as websocket server.

I think the main difference between websocket and http streaming (I am not refering to polling and long polling) is websocket allows bi-directional communication which is similar to usual raw socket programming. (above is my understanding, could be wrong, feel free to correct me.)

My question is how the web client (browser) continue to send another request through the already-opened websocket? Usual http request will treat another request as new socket connection, but websocket does not, that is why I am confused, how it achieve that? It should be handled in Server side or Client (browser) side?

Yes, websockets are bidirectional. An important consequence is that you may efficiently push data from the server to the client.

Underlying sockets are just kept open (or reopened when needed if they couldn't be kept open). Note that HTTP 1.1 yet did that :

HTTP/1.1 is a revision of the original HTTP (HTTP/1.0). In HTTP/1.0 a separate connection to the same server is made for every resource request. HTTP/1.1 can reuse a connection multiple times to download images, scripts, stylesheets et cetera after the page has been delivered. HTTP/1.1 communications therefore experience less latency as the establishment of TCP connections presents considerable overhead.

It must be handled both client-side and server-side. Of course that implies that both software be updated ( old browsers and old servers can't handle websockets).

EDIT (following exchanges in comment) :

Client side, here's how a connection can be initialized :

var ws = new WebSocket('ws://'+document.location.host+'/ws');
ws.onopen = function() {
       // do something
};
ws.onerror = function() {
       // do something
};
ws.onclose = function() {
       // do something
};
ws.onmessage = function(msgevent) {
    var msg = JSON.parse(msgevent.data);
    // handle incoming message
};

You keep the ws variable, and after that you may push from client to server using the same connection with

ws.send(window.JSON.stringify(msg)); // msg is a basic js object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM