首页 > 解决方案 > 将 .NET WebSockets 客户端连接到 node.js socket.io 服务器

问题描述

我目前支持一个较旧的应用程序,它有一个带有 socket.io (v1.3.7) 连接的 node.js (v0.12.13) 服务器。该服务器很好地支持浏览器客户端。

socket.attach(http, { 'transports': ['polling','websocket'], 'allowUpgrades': true });
socket.attach(https, { 'transports': ['polling','websocket'], 'allowUpgrades': true });
socket.sockets.on('connection', function (socket) {
    // Process stuff here
});

我们的要求还要求我们允许我们的旧版 Windows 应用程序连接到节点服务器,并且我使用过SocketIoClientDotNet / EngineIoClientDotNet,这或多或少可以正常工作(有一些我需要处理的例外情况)。

所以我想我会尝试使用 .NET ClientWebSocket 方法,其中 uri="ws://10.10.5.112",基于这篇文章

static async Task Connect(string uri)
{
    ClientWebSocket sock = new ClientWebSocket();
    await sock.ConnectAsync(new Uri(uri), CancellationToken.None);
}

但我得到以下例外:

System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at WebsocketClientTest.Program.Main(String[] args) in C:\Source\test\WebsocketClientTest\Program.cs:line 16

Inner Exception 1:
WebSocketException: Unable to connect to the remote server

Inner Exception 2:
WebException: The underlying connection was closed: The connection was closed unexpectedly.

果然,我在服务器上看不到任何连接尝试,但 Wireshark 告诉我 .Net 应用程序正在尝试启动连接,但没有从 node.js 服务器得到响应。看起来这是 socket.io 方面的失败,但任何可以帮助我的想法都值得赞赏。

Wireshark 跟踪

标签: c#.netwebsocketsocket.io.net-4.6

解决方案


推荐阅读