简体   繁体   中英

Understanding how HTTP GET upgrades to Web Sockets

I am misunderstanding how to set up a web socket connection between a client and a server.

In my mind, an HTTP GET request expects a response, and then that is the full lifetime of the request. When talking about web sockets now I am reading that the server responds with a 101 (Switching Protocols) and then magically(?) opens a web socket connection to that client. How, on the client-side, do they handle the (again, magic?) stream of data that the server may now send them?

In my mind a regular request may be executed as such:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://localhost/something");
request.Method = "GET";
request.GetResponse();
        

Even if that GetResponse() returned a 101 , what more has to be done on the client-side to receive data? On the server-side?

I am looking for a pointer to some documentation that highlights the actual implementation. I prefer to not use a library in a specific language as I want any client to be able to initiate a web socket connection through a normal HTTP GET request.

RFC 6455 (The WebSocket Protocol) is the document for you to read. You can find the description about the opening handshake in 4. Opening Handshake .

It's written in Java (not in C#), but you can consult nv-websocket-client prior to implementing your own WebSocket client library in C#.

You need to use System.Net.WebSockets.ClientWebSocket to access a WebSocket server.

What happens after that HTTP 101, is that the connection is not considered ASCII based anymore, and it is considered a binary connection, where the WebSocket framing protocol comes into action, that is why you need a client websocket component, because you cannot write directly on the socket, you have to frame the information in messages as the RFC explains.

Writing you own client would be very didactic, but not very productive.

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