我正在尝试使用 Workbench 中的 Vala example 连接到 Revolt(聊天应用程序)的 websocket,但似乎我在身份验证时没有收到预期的就绪事件。反抗文档:
身份验证后,服务器将响应 Authenticated,然后发送包含有用数据的 Ready 事件。
我检查 http 状态代码,得到 101 Switching Protocols。
我不知道在这种情况下该如何进行。 Workbench 示例似乎可以与他们提供的示例 websocket 一起使用。
值得注意的是,我是 Vala 和整个网络堆栈的新手,我无法找到 Vala 的在线示例。
这是我到目前为止的代码:
class WebsocketClient : Object {
private Soup.Session session;
private Soup.WebsocketConnection connection;
private string user_token;
public WebsocketClient (Soup.Session global_session, string user_token) {
this.session = global_session;
this.user_token = user_token;
Soup.Message request = new Soup.Message ("GET", @"wss://ws.revolt.chat?format=json&token=$(user_token)");
session.websocket_connect_async.begin (request, null, null, 1, null, (obj, res) => {
try {
connection = session.websocket_connect_async.end (res);
} catch (Error error_thing) {
error (error_thing.message);
}
connection.error.connect (on_error);
connection.closed.connect (on_closed);
connection.message.connect (on_message);
// on_open ();
});
}
private void on_message (int type, Bytes msg) {
if (type != Soup.WebsocketDataType.TEXT) return;
string response = (string) msg.get_data ();
message(response);
}
// other methods...
}
我在另一个文件中创建 websocket。
鉴于valadoc的解释,我希望切换自动发生或自己处理,但我找不到
Session.websocket_connect_finish
方法。
如果服务器返回“101 Switching Protocols”,则msg的状态码和响应头将被更新,然后WebSocket握手将完成。成功后,[[email protected]_connect_finish] 将返回一个新的 [class@WebsocketConnection]。失败时它将返回错误。
我愚蠢的傻瓜自己忘记了
async
的事情。我必须将连接逻辑移至 async
方法内,并在其他地方调用该方法。