简体   繁体   English

了解 HTTP GET 如何升级到 Web Sockets

[英]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.我误解了如何在客户端和服务器之间设置 Web 套接字连接。

In my mind, an HTTP GET request expects a response, and then that is the full lifetime of the request.在我看来,一个HTTP GET请求需要一个响应,这就是请求的整个生命周期。 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.现在谈论网络套接字时,我读到服务器以101 (Switching Protocols)响应,然后神奇地(?)打开与该客户端的网络套接字连接。 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?即使GetResponse()返回101 ,客户端还需要做什么来接收数据? 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.我不喜欢使用特定语言的库,因为我希望任何客户端都能够通过正常的HTTP GET请求启动 Web 套接字连接。

RFC 6455 (The WebSocket Protocol) is the document for you to read. RFC 6455 (WebSocket 协议)是供您阅读的文档。 You can find the description about the opening handshake in 4. Opening Handshake .可以在4. 开启握手中找到关于开启握手的描述。

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#.它是用 Java(而不是 C#)编写的,但在用 C# 实现您自己的 WebSocket 客户端库之前,您可以咨询nv-websocket-client

You need to use System.Net.WebSockets.ClientWebSocket to access a WebSocket server.您需要使用System.Net.WebSockets.ClientWebSocket来访问 WebSocket 服务器。

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.在 HTTP 101 之后会发生什么,连接不再被认为是基于 ASCII 的,它被认为是一个二进制连接,WebSocket 帧协议开始起作用,这就是为什么你需要一个客户端 websocket 组件,因为你不能直接写在套接字上,您必须按照RFC 的说明在消息中构建信息。

Writing you own client would be very didactic, but not very productive.编写你自己的客户端会很有教益,但效率不高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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