通过c#与socket.io服务器通信



是否有遵循socket.io协议的c#客户端?我有一个socket.io服务器,它通过网站与socket.io javascript客户端通信,但我还需要连接一个可以发送和接收消息的c#部件。目前有没有一种干净的方法可以做到这一点,或者我必须写我自己的客户。

codeplex上有一个项目(NuGet也是),它是socket.io的C#客户端。(我是这个项目的作者,所以我有偏见)我无法在客户身上找到我需要的东西,所以我构建了它,并将其重新公开。

示例客户端样式:

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

使用以下库:https://github.com/sta/websocket-sharp它可以通过NuGet:获得

PM> Install-Package WebSocketSharp -Pre

要连接到Socket.IO 1.0+服务器,请使用以下语法:

using (var ws = new WebSocket("ws://127.0.0.1:1337/socket.io/?EIO=2&transport=websocket"))
{
    ws.OnMessage += (sender, e) =>
      Console.WriteLine("New message from controller: " + e.Data);
    ws.Connect();
    Console.ReadKey(true);
}

换句话说,将其附加到localhost:port-"socket.io/?EIO=2&transport=websocket"。

我的完整服务器代码:https://gist.github.com/anonymous/574133a15f7faf39fdb5

此包支持最新的协议
Github-https://github.com/HavenDV/H.Socket.IO/
C#现场示例-https://dotnetfiddle.net/FWMpQ3/
VB.NET现场示例-https://dotnetfiddle.net/WzIdnG/
Nuget:

Install-Package H.Socket.IO
using System;
using System.Threading.Tasks;
using H.Socket.IO;
#nullable enable
public class ChatMessage
{
    public string? Username { get; set; }
    public string? Message { get; set; }
    public long NumUsers { get; set; }
}
    
public async Task ConnectToChatNowShTest()
{
    await using var client = new SocketIoClient();
    client.Connected += (sender, args) => Console.WriteLine($"Connected: {args.Namespace}");
    client.Disconnected += (sender, args) => Console.WriteLine($"Disconnected. Reason: {args.Reason}, Status: {args.Status:G}");
    client.EventReceived += (sender, args) => Console.WriteLine($"EventReceived: Namespace: {args.Namespace}, Value: {args.Value}, IsHandled: {args.IsHandled}");
    client.HandledEventReceived += (sender, args) => Console.WriteLine($"HandledEventReceived: Namespace: {args.Namespace}, Value: {args.Value}");
    client.UnhandledEventReceived += (sender, args) => Console.WriteLine($"UnhandledEventReceived: Namespace: {args.Namespace}, Value: {args.Value}");
    client.ErrorReceived += (sender, args) => Console.WriteLine($"ErrorReceived: Namespace: {args.Namespace}, Value: {args.Value}");
    client.ExceptionOccurred += (sender, args) => Console.WriteLine($"ExceptionOccurred: {args.Value}");
    
    client.On("login", () =>
    {
        Console.WriteLine("You are logged in.");
    });
    client.On("login", json =>
    {
        Console.WriteLine($"You are logged in. Json: "{json}"");
    });
    client.On<ChatMessage>("login", message =>
    {
        Console.WriteLine($"You are logged in. Total number of users: {message.NumUsers}");
    });
    client.On<ChatMessage>("user joined", message =>
    {
        Console.WriteLine($"User joined: {message.Username}. Total number of users: {message.NumUsers}");
    });
    client.On<ChatMessage>("user left", message =>
    {
        Console.WriteLine($"User left: {message.Username}. Total number of users: {message.NumUsers}");
    });
    client.On<ChatMessage>("typing", message =>
    {
        Console.WriteLine($"User typing: {message.Username}");
    });
    client.On<ChatMessage>("stop typing", message =>
    {
        Console.WriteLine($"User stop typing: {message.Username}");
    });
    client.On<ChatMessage>("new message", message =>
    {
        Console.WriteLine($"New message from user "{message.Username}": {message.Message}");
    });
    
    await client.ConnectAsync(new Uri("wss://socketio-chat-h9jt.herokuapp.com/"));
    await client.Emit("add user", "C# H.Socket.IO Test User");
    await Task.Delay(TimeSpan.FromMilliseconds(200));
    await client.Emit("typing");
    await Task.Delay(TimeSpan.FromMilliseconds(200));
    await client.Emit("new message", "hello");
    await Task.Delay(TimeSpan.FromMilliseconds(200));
    await client.Emit("stop typing");
    await Task.Delay(TimeSpan.FromSeconds(2));
    await client.DisconnectAsync();
}

它还支持名称空间:

// Will be sent with all messages(Unless otherwise stated).
// Also automatically connects to it.
client.DefaultNamespace = "my";
// or
// Connects to "my" namespace.
await client.ConnectAsync(new Uri(LocalCharServerUrl), cancellationToken, "my");
// Sends message to "my" namespace.
await client.Emit("message", "hello", "my", cancellationToken);

我发现了另一个.Net库,它与socket.io配合得很好。它也是更新最多的。按照下面的链接,

Quobject/SocketIoClientDotNet

using Quobject.SocketIoClientDotNet.Client;
var socket = IO.Socket("http://localhost");
socket.On(Socket.EVENT_CONNECT, () =>
{
    socket.Emit("hi");
});
socket.On("hi", (data) =>
{
    Console.WriteLine(data);
    socket.Disconnect();
});
Console.ReadLine();

希望,它能帮助别人。

我尝试了以上所有操作,但不知何故,他们没有与我正在集成的服务进行对话(也许服务有问题,我不知道是哪个)。所以我写了我自己的。

https://github.com/it9gamelog/socketio-with-ws-client

一个极简主义的单文件客户端实现。由于socket-io是一种正在消亡的技术,而且规范非常复杂,所以任何一方的错误都可能永远无法修复。单文件方法至少更易于调优、扩展和调试。

这取决于Web服务器的外观。在某些情况下,也可以为常规套接字创建侦听器
否则,您可能不得不创建自己的客户。然而,您可能只需要实现WebSocket传输,所以它无论如何都应该相当简单。

值得一提的是,我建议看看"是否有一个为.NET实现的WebSocket客户端?"和我的(相当简单的)WebSocket Socket.IO传输客户端为Java实现。

相关内容

  • 没有找到相关文章

最新更新