【发布时间】:2020-02-29 21:24:58
【问题描述】:
我为测试编写了一个客户端和服务器。客户:
static Soup.WebsocketConnection websocket;
int main (string[] args)
{
var ws_session = new Soup.Session();
var ws_message = new Soup.Message("GET", "http://127.0.0.1:8088/");
string[] protocols = {"chat"};
var ws_loop = new MainLoop();
ws_session.websocket_connect_async.begin(ws_message, "localhost", protocols, null, (obj, res) => {
websocket = ws_session.websocket_connect_async.end(res);
websocket.message.connect(rec_message);
});
ws_loop.run();
stdout.printf("Program end. Press ENTER"); // the program does not reach this point
stdin.read_line();
websocket.close(0, null);
return 0;
}
void rec_message(int type, Bytes message){
stdout.printf("WebSock receive:\n");
stdout.printf("%s\n".printf((string)message.get_data()));
websocket.send_text("test_message2"); // client does not send message
}
和服务器:
public class WSServer : Soup.Server {
private int access_counter = 0;
public WSServer(){
assert (this != null);
string[] protocols = {"chat"};
this.add_websocket_handler(null,"localhost", protocols, get_ws);
}
void get_ws(Soup.Server server, Soup.WebsocketConnection connection, string path, Soup.ClientContext client){
connection.message.connect(ws_message);
string host = client.get_host();
info (@"Client connected! Host: $host");
string msg = """test_message1""";
info (@"Sending to client message: $msg");
connection.send_text(msg);
}
void ws_message(int id, Bytes msg){
string message = (string)msg.get_data();
info(@"Message received! ID: $id Message:\n$message\n");
}
}
int main (string[] args)
{
try {
int port = 8088;
MainLoop loop = new MainLoop ();
WSServer server = new WSServer ();
server.listen_local (port, 0);
loop.run ();
} catch (Error e) {
error ("Error: %s\n", e.message);
}
stdout.printf("Programm end. Press ENTER");
stdin.read_line ();
return 0;
}
服务器和客户端启动后,发生第一条消息的连接和交换test_message1,之后服务器关闭连接,不再接收消息。客户端尝试发送消息test_message2,然后用代码和错误消息关闭连接:WS Error 44: Error receiving data: Connection reset by peer
【问题讨论】:
-
一旦你建立了连接,你可能想要
steal_connection来获得IOStream。然后您可以使用DataInputStream和DataOutputStream方便地通过连接进行通信。这个Valum code 可能是一个很好的起点 -
@AlThomas 我使用 Soup 来配置、维护和处理流。它有一个WebsocketConnection类,提供消息接收信号和发送功能。
-
我假设你使用valadoc.org/libsoup-2.4/…?
-
@AlexB 是的,我添加了一个示例
-
那个例子不完整(rec_message 在哪里?)你几乎肯定不想在那里打电话给
loop.quit();,你在打开连接后就退出了程序
标签: http web websocket vala libsoup