Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who is sending http websocket upgrade requests?

Websocket? Or XMLHttpRequest? Or I have to do it myself?

So I understand the client has to send it, but when and why? Suppose I use the XMLHttpRequest object to send a normal HTTP GET. I have no control over how long that internal tcp connection in the browser lasts, right? And if I want to use websockets I have to use their own websocket classes anyway, so for me as a user, "upgrading" is not visible, is it? It's just the browser that is doing some internal magic to reuse a connection, the whole upgrade process is irrelevant for me as a user? I still have to use two different classes, I just happen to use the same port and the browser then decides for performance reasons to upgrade. Is that really correct?

like image 996
Blub Avatar asked Dec 07 '22 00:12

Blub


1 Answers

No, the WebSocket clients sends the HTTP request asking for a WebSocket connection, then the server responds with an HTTP 101 Switching protocols, meaning that it accepts the connection, and then the client can start to send and receive data in binary format.

Example client request:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

Example server response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

It is well explained in the Wikipedia article: http://en.wikipedia.org/wiki/WebSocket#WebSocket_protocol_handshake

And it is detailed in the spec: https://www.rfc-editor.org/rfc/rfc6455#section-1.3

It's just the browser that is doing some internal magic to reuse a connection, the whole upgrade process is irrelevant for me as a user?

That is right.

I still have to use two different classes, I just happen to use the same port and the browser then decides for performance reasons to upgrade. Is that really correct?

If you want to use AJAX you use XMLHttpRequest. If you want to use WebSocket, you use the WebSocket class. Still, they can be accessed by the same port. The difference is that the WebSocket connection will negotiate with the server a full duplex persistent binary channel, while the XMLHttpRequest will just make a request and get a response.

like image 198
vtortola Avatar answered Dec 19 '22 00:12

vtortola