【问题标题】:Not being able to receive messages from websocket server无法从 websocket 服务器接收消息
【发布时间】:2016-07-26 14:51:50
【问题描述】:

不知道为什么收不到服务器发来的数据。

服务器是使用https://github.com/websockets/ws 用node.js 编写的,我使用他们的示例来设置服务器。这就是我发送数据的方式:

wss.on('connection', function connection(ws) {

   ws.on('open', function (){
   ws.send('You are logged');
   })

   ws.send('something');
});

这就是我在 c# 中使用 ClientWebSocket 接收数据的方式

public static async Task ReceiveData(ClientWebSocket ws)
    {
        ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);

        WebSocketReceiveResult result = null;
        while (ws.State == WebSocketState.Open)
           {
               using (var ms = new MemoryStream())
               {
                    do
                    {
                        result = await ws.ReceiveAsync(buffer, CancellationToken.None);
                        ms.Write(buffer.Array, buffer.Offset, result.Count);
                     }
                     while (!result.EndOfMessage);

                     ms.Seek(0, SeekOrigin.Begin);

                    using (var reader = new StreamReader(ms, Encoding.UTF8))
                         Console.WriteLine( reader.ReadToEnd());
              }
           }
    }

问题是我收到“某物”一次。我的目标是希望每秒收到“您已登录”的消息?

编辑:澄清...问题是 ws.on('open',..) 中的消息由于某种原因没有发送?

感谢您的时间:)

【问题讨论】:

    标签: c# node.js websocket


    【解决方案1】:
    ws.on('open', function (){
        ws.send('You are logged'); 
        var timer = setInterval(function() {
            if (ws) 
                ws.send('You are logged');
            else
                clearInterval(timer);
        }, 1000);
    });
    

    ?

    【讨论】:

    • 问题是 ws.on('open', function(){ws,send('some message') ;} 中的消息根本没有发送。我收到的唯一字符串是 ws.on('open',...) 之后的“某物”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2019-09-22
    • 2021-02-28
    相关资源
    最近更新 更多