3

我有 laravel 聊天应用程序通过 laravel-echo-server 上的 laravel 广播工作。在前端,我使用 laravel-echo npm 包订阅频道并收听事件,但是如何订阅用 c# 编写的桌面应用程序中的频道?

我希望在 c# 上写下这样的内容:

Echo.private('SomeChannel')
    .listen('SomeEvent', (response) => {});
4

1 回答 1

1

安装https://github.com/doghappy/socket.io-client-csharp

using Newtonsoft.Json;
using SocketIOClient.WebSocketClient;
using SocketIOClient;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;

namespace c_sharp_demo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
             var uri = new Uri("http://localhost:6001");

             var socket = new SocketIO(uri, new SocketIOOptions
            {
                Query = new Dictionary<string, string>
                {
                    {"token", "io" }
                }
            });

            socket.OnConnected += Socket_OnConnected;
            socket.OnPing += Socket_OnPing;
            socket.OnPong += Socket_OnPong;
            socket.OnDisconnected += Socket_OnDisconnected;
            socket.OnReconnecting += Socket_OnReconnecting;
            try
            {
                await socket.ConnectAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }

            socket.On("event-name", response =>
            {
                Console.WriteLine($"server: {response}");
            });

            Console.ReadLine();
        }

        private static async void Socket_OnConnected(object sender, EventArgs e)
        {
            Console.WriteLine("Socket_OnConnected");
            var socket = sender as SocketIO;

            await socket.EmitAsync("subscribe", new
            {
               channel = "channelName",
               auth = ""
            });
        }

         private static void Socket_OnPing(object sender, EventArgs e)
        {
            Console.WriteLine("Ping");
        }

        private static void Socket_OnPong(object sender, TimeSpan e)
        {
            Console.WriteLine("Pong: " + e.TotalMilliseconds);
        }

        private static void Socket_OnDisconnected(object sender, string e)
        {
            Console.WriteLine("disconnect: " + e);
        }

        private static void Socket_OnReconnecting(object sender, int e)
        {
            Console.WriteLine($"Reconnecting: attempt = {e}");
        }
    }
}
 
于 2020-11-12T10:03:17.413 回答