将消息从UWP发送到socket.io

时间:2017-08-21 09:25:13

标签: c# node.js sockets socket.io uwp

我有一个简单的节点socket.io服务器和一个C#UWP应用程序。 我想从应用程序向服务器发送简单的消息,但似乎消息的格式/协议/格式不正确。 我试图让格式正确,但我不知道该怎么做。

app.js

io.on('connection', function(socket){
  console.log('CLIENT CONNECTED')

  socket.on('message', function (msg) {
    console.log('socket msg')
    console.log(msg)
}

当我从socket.io tester触发消息时,控制台会显示

socket msg
dwadwadwada

(就像它应该的那样)

调试输出:

 engine:socket packet +1ms
  socket.io-parser decoded 2["message","dwadwadwada"] as {"type":2,"nsp":"/","data":["message","dwadwadwada"]} +0ms
  socket.io:socket got packet {"type":2,"nsp":"/","data":["message","dwadwadwada"]} +0ms
  socket.io:socket emitting event ["message","dwadwadwada"] +0ms
  socket.io:socket dispatching an event ["message","dwadwadwada"] +0ms

现在,如果我从我的UWP应用程序发送一个字符串(为了简洁,删除了try / catches和异常处理)

string msg = "test";
await sendMessage(msg);

private async Task sendMessage(string message)
{
    this.socket = new MessageWebSocket();
    socket.Control.MessageType = SocketMessageType.Utf8;
    socket.MessageReceived += socketMsgReceived;
    await this.socket.ConnectAsync(uri);
    Debug.WriteLine("CONNECTED TO " + uri);

    DataWriter messageWriter = new DataWriter(socket.OutputStream);

    messageWriter.WriteString(message);
    await messageWriter.StoreAsync();
}

,邮件被发送(没有错误),服务器似乎得到某些东西,但它不被识别为消息。

 engine:ws received "test" +6s
  engine:socket packet +1ms
  engine:ws closing +1ms
  socket.io:client client close with reason parse error +0ms
  socket.io:socket closing socket - reason parse error +1ms

我尝试将邮件格式化为 {message = "test"}甚至42["message","test"]没有效果,即使后者至少给了我

  engine:ws received "42["message" = "test"]" +4s
  engine:socket packet +0ms
  socket.io-parser decoded 2["message" = "test"] as {"type":4,"data":"parser error"} +0ms
  socket.io:client no socket for namespace undefined +1ms

我很确定这是一个简单的修复,但我无法找到如何做到这一点.. 我必须将其转换为特殊类型吗?以某种方式JSONify它? 我不想要任何花哨的东西,只需发送一个

{message: "hi"}

或者(在第一个工作之后)

{message: {text: "hi", additionalStuff: "ho"}}

我很感激任何帮助:) 谢谢!

1 个答案:

答案 0 :(得分:0)

我发现了问题是什么......

我真的不得不手工构建websocket字符串,因为(我注意到了)socket.io实际上与websockets不同,只是一个包装器。

所以我必须从头开始使用here中的信息构建一个JSON字符串。

我的最后一个字符串看起来像

 "42[\"mess\"," +
 "{\"id\": \"" + id + "\", " +
 "\"name\": \"" + name + "\"}]";

有很多转义报价...我真的不明白为什么它是 42 而不是“4”,就像文档说的消息一样,但我发现这就是实际发送的内容,所以我只是用它(它有效)

上面的消息由

解析
socket.on('mess', function(msg) {
    console.log(msg) 
}

作为

{id: blah, name: bleh}