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

能否用C#创建Socket.IO服务器?控制台应用搭建方法咨询

Absolutely you can build a Socket.IO server in C#—you just need to know the right libraries to use! I’ve helped plenty of developers set this up for console apps, so let’s break down the best options and walk through a working implementation.

1. Top Libraries for C# Socket.IO Servers

There are a couple of reliable libraries that support Socket.IO server functionality in .NET:

  • SocketIO4Net.Server: A mature, battle-tested library that works seamlessly with console apps (and ASP.NET projects). It supports multiple Socket.IO protocol versions, so you won’t run into compatibility issues with most clients.
  • Socket.IO.AspNetCore: If you’re open to leveraging ASP.NET Core (even in a console app), this is a modern, polished option that integrates smoothly with ASP.NET Core’s hosting model, giving you access to features like middleware and dependency injection.
2. Step-by-Step: Console App with SocketIO4Net.Server

Let’s start with a straightforward console implementation using SocketIO4Net.Server:

First, Install the NuGet Package

Open your console app project, then run this command in the Package Manager Console:

Install-Package SocketIO4Net.Server

Or search for SocketIO4Net.Server in the NuGet Package Manager UI and install it.

Next, Write the Server Code

Replace your Program.cs with this code:

using System;
using SocketIO4Net.Server;
using WebSocketSharp.Server;

namespace SocketIoConsoleServer
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a WebSocket server on port 3000
            var webSocketServer = new WebSocketServer("ws://localhost:3000");
            
            // Add our custom Socket.IO handler to the server
            webSocketServer.AddWebSocketService<SocketIoHandler>("/socket.io/");
            
            // Start the server
            webSocketServer.Start();
            Console.WriteLine("Socket.IO server is running at ws://localhost:3000");
            Console.WriteLine("Press any key to shut down the server...");
            Console.ReadKey();
            
            // Clean up and stop the server
            webSocketServer.Stop();
        }
    }

    // Custom handler to manage Socket.IO connections and events
    public class SocketIoHandler : WebSocketBehavior
    {
        private SocketIoServer _socketIoServer;

        protected override void OnOpen()
        {
            // Set up the Socket.IO server with basic options
            _socketIoServer = new SocketIoServer(Context, new SocketIOOptions
            {
                AutoUpgrade = true,
                // Support both websocket and polling transports for broader client compatibility
                Transports = new[] { "websocket", "polling" }
            });
            
            // Listen for new client connections
            _socketIoServer.On("connection", (clientSocket) =>
            {
                Console.WriteLine($"New client connected: {clientSocket.Id}");
                
                // Listen for a "message" event from the client
                clientSocket.On("message", (messageData) =>
                {
                    Console.WriteLine($"Received from {clientSocket.Id}: {messageData}");
                    
                    // Send a response back to the client
                    clientSocket.Emit("server-response", $"Got your message: {messageData}");
                });
                
                // Listen for client disconnections
                clientSocket.On("disconnect", () =>
                {
                    Console.WriteLine($"Client disconnected: {clientSocket.Id}");
                });
            });
            
            _socketIoServer.Start();
        }

        protected override void OnMessage(string message)
        {
            // Pass incoming messages to the Socket.IO server for processing
            _socketIoServer.OnMessage(message);
        }

        protected override void OnClose(WebSocketSharp.CloseEventArgs e)
        {
            // Clean up when the connection closes
            _socketIoServer.Stop();
            base.OnClose(e);
        }
    }
}

How This Works

  • We create a WebSocket server to handle the underlying transport, then attach a Socket.IO handler to it.
  • The SocketIoHandler class manages client connections, listens for events like message, and sends responses back.
  • We support both websocket and polling transports to ensure compatibility with older or restricted client environments.
3. Alternative: ASP.NET Core in a Console App

If you prefer a more modern approach, you can host an ASP.NET Core Socket.IO server directly in a console app. This gives you access to ASP.NET Core’s ecosystem, which is great if you need to add more features later.

Install Required Packages

Run these commands in the Package Manager Console:

Install-Package Microsoft.AspNetCore.App
Install-Package Socket.IO.AspNetCore

Write the Server Code

Here’s a minimal implementation:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AspNetCoreSocketIoConsoleServer
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            
            // Add Socket.IO services to the dependency injection container
            builder.Services.AddSocketIO();
            
            var app = builder.Build();
            
            // Map the Socket.IO endpoint
            app.MapSocketIO("/socket.io");
            
            // Configure Socket.IO event handlers
            app.UseSocketIO(socket =>
            {
                socket.On("connection", () =>
                {
                    Console.WriteLine($"Client connected: {socket.Id}");
                    
                    socket.On("message", (data) =>
                    {
                        Console.WriteLine($"Received: {data}");
                        socket.Emit("server-response", $"Server received your message: {data}");
                    });
                    
                    socket.On("disconnect", () =>
                    {
                        Console.WriteLine($"Client disconnected: {socket.Id}");
                    });
                });
            });
            
            // Start the server on port 3000
            app.Run("http://localhost:3000");
        }
    }
}
4. Testing Your Server

To make sure everything works, you can use a simple Node.js client:

  1. Install socket.io-client via npm: npm install socket.io-client
  2. Create a client.js file with this code:
const io = require('socket.io-client');
const socket = io('http://localhost:3000');

socket.on('connect', () => {
    console.log('Connected to C# Socket.IO server!');
    socket.emit('message', 'Hello from Node.js client!');
});

socket.on('server-response', (response) => {
    console.log(response);
});
  1. Run the client with node client.js—you should see the connection and response logs in both your console server and client.

Important Note

Make sure the Socket.IO protocol versions match between your server and clients. For example, if your server uses Socket.IO v4, use a v4 client library to avoid compatibility issues.

内容的提问来源于stack exchange,提问作者Kenneth Gomez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:57:45