You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#连接基于Node.js Express搭建的Socket.IO服务器?

Socket.IO C# 客户端无法连接 Node.js 服务器的解决方案

以下是几个实用的排查和修复方向,你可以逐一尝试:

1. 版本兼容性检查

Socket.IO 客户端与服务器版本必须匹配,Quobject SocketIoClientDotNet 目前最高支持到 Socket.IO v3.x。如果你的 Node.js 服务器使用 v4.x 及以上版本,两者会出现兼容问题:

  • 查看服务器端 package.json 里的 socket.io 版本
  • 若版本不匹配:要么降级服务器的 socket.io 到 v3.x,要么更换支持更高版本的 C# Socket.IO 客户端(比如 Socket.IO.Client NuGet 包)

2. 修正连接 URL 协议

Socket.IO 初始化需要先通过 HTTP 完成握手,再升级到 WebSocket,因此 C# 客户端应使用 http:// 协议而非 ws://:

string serverUrl = "http://192.168.10.210:8989";

3. 添加错误监听排查问题

在 C# 代码中添加错误、断开事件监听,能直接获取连接失败的具体原因:

// 新增错误监听
socket.On(Socket.EVENT_CONNECT_ERROR, (error) =>
{
    Console.WriteLine($"连接错误: {error}");
});

socket.On(Socket.EVENT_DISCONNECT, (reason) =>
{
    Console.WriteLine($"断开连接: {reason}");
});

socket.On(Socket.EVENT_CONNECT_TIMEOUT, () =>
{
    Console.WriteLine("连接超时");
});

4. 配置服务器端 CORS

Node.js 服务器如果未配置跨域,会阻止非浏览器客户端的连接。修改服务器初始化代码,添加 CORS 配置:

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
// 新增 CORS 配置
const socketIO = new Server(server, {
    cors: {
        origin: "*", // 生产环境请替换为具体客户端地址
        methods: ["GET", "POST"]
    }
});

socketIO.on("connection", function (socket) {
    console.log(socket.id);

    socket.on("connected", function (userId) {
        console.log(userId);
        users[userId] = socket.id;
    });
});

server.listen(8989, () => {
    console.log('服务器运行在 8989 端口');
});

5. 修正后的完整 C# 代码

using Quobject.SocketIoClientDotNet.Client;

class Program
{
    static void Main(string[] args)
    {
        int applicationId = 1;
        // 改用 http 协议
        string serverUrl = "http://192.168.10.210:8989";

        var socket = IO.Socket(serverUrl);

        socket.On(Socket.EVENT_CONNECT, () =>
        {
            Console.WriteLine("Connected to server");
            socket.Emit("connected", applicationId);
        });

        socket.On("messageReceived", data =>
        {
            Console.WriteLine(data);
        });

        // 新增错误监听
        socket.On(Socket.EVENT_CONNECT_ERROR, (error) =>
        {
            Console.WriteLine($"连接错误: {error}");
        });

        socket.On(Socket.EVENT_DISCONNECT, (reason) =>
        {
            Console.WriteLine($"断开连接: {reason}");
        });

        Console.ReadLine();
        socket.Disconnect();
    }
}

内容的提问来源于stack exchange,提问作者Freedom Rider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 09:00:02