服务器发送关闭信号时使用libcurl关闭Websocket连接 [英] Closing websocket connections using libcurl when server sends close signal

查看:221
本文介绍了服务器发送关闭信号时使用libcurl关闭Websocket连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是高级用户,所以请应付我.

我正在尝试使用libcurl实现WebSocket客户端,直到连接的最后一步-终止,我都很好.

一般逻辑如下:

  1. 客户端连接并发送升级请求.
  2. Websocket服务器接受/升级并开始发送乱码.
  3. 客户累加了所有乱码.
  4. 服务器在10秒后发送关闭信号.

到目前为止,一切都很好.我不处理传入消息的有效负载,而且我也不想这样做.我的资源非常有限,不想为了检查每个有效负载并搜索关闭信号而遭受任何性能损失.

我正在使用libcurl的 easy 界面,并使用 curl_easy_perform()接收数据.有什么方法可以检测到关闭信号,或者在10秒后关闭websocket连接?

解决方案

关闭信号是框架层WebSocket协议的一部分(请参阅RFC 6455部分5 5.5.1 ).

AFAIK,libcurl本身不支持WebSocket,仅支持HTTP(WebSocket用于其打开握手,因此您可以使用libcurl对其进行伪造).因此,如果libcurl无法为您处理WebSocket框架,则即使您忽略它们的有效负载,也必须自己处理它们.

否则,只需为自己设置一个10秒的计时器并直接关闭基础TCP连接,您可以使用 解决方案

Close signals are part of the WebSocket protocol at the framing layer (see RFC 6455 Sections 1.4, 5, and 5.5.1).

AFAIK, libcurl doesn't natively support WebSockets, just HTTP (which a WebSocket uses for its opening handshake, so you can fake it with libcurl). So, if libcurl doesn't process the WebSocket frames for you, you would have to process them yourself, even if you ignore their payloads.

Otherwise, just set a 10-second timer for yourself and close the underlying TCP connection directly, which you can get from libcurl using curl_easy_getinfo(CURLINFO_ACTIVESOCKET).

But, if the server is sending you a close signal, you SHOULD send one back, per Section 5.5.1, which means parsing the frames properly:

If an endpoint receives a Close frame and did not previously send a Close frame, the endpoint MUST send a Close frame in response. (When sending a Close frame in response, the endpoint typically echos the status code it received.) It SHOULD do so as soon as practical. An endpoint MAY delay sending a Close frame until its current message is sent (for instance, if the majority of a fragmented message is already sent, an endpoint MAY send the remaining fragments before sending a Close frame). However, there is no guarantee that the endpoint that has already sent a Close frame will continue to process data.

After both sending and receiving a Close message, an endpoint considers the WebSocket connection closed and MUST close the underlying TCP connection. The server MUST close the underlying TCP connection immediately; the client SHOULD wait for the server to close the connection but MAY close the connection at any time after sending and receiving a Close message, e.g., if it has not received a TCP Close from the server in a reasonable time period.

If a client and server both send a Close message at the same time, both endpoints will have sent and received a Close message and should consider the WebSocket connection closed and close the underlying TCP connection.

这篇关于服务器发送关闭信号时使用libcurl关闭Websocket连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆