簡體   English   中英

Node.js與C#通信

[英]nodejs ws comunicate with c#

我想將C#應用程序與Node.JS websocket服務器進行通信。

 const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 9011 });

wss.on('connection', function connection(ws) {
    console.log("connected");
    ws.on('message', function incoming(message) {
       ws.send('new status ', status);            
    });
   ws.on("test", function incoming(message)
   {
       console.log(message);
   }); 
});

如何將Websocket與c#.net連接以及如何運行它

上(測試)事件

您可能想看看以下庫: https : //github.com/sta/websocket-sharp

用法示例(自述文件中):

using System;
using WebSocketSharp;

namespace Example
{
  public class Program
  {
    public static void Main (string[] args)
    {
      using (var ws = new WebSocket ("ws://dragonsnest.far/Laputa")) {
        ws.OnMessage += (sender, e) =>
            Console.WriteLine ("Laputa says: " + e.Data);

        ws.Connect ();
        ws.Send ("BALUS");
        Console.ReadKey (true);
      }
    }
  }
}

這將是使用WebSocket類的原始實現。

using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Linq;

public class Program
  {
    public static async Task Main (string[] args)
    {
        string address="localhost"; //server address 
        int port=9011;
        ClientWebSocket socket=new ClientWebSocket();
        CancellationTokenSource src=new CancellationTokenSource();
        try
        {
             await socket.ConnectAsync(new Uri($"ws://{address}:{port.ToString()}"));
             Task receiveTask=Task.Run(async()=>await LoopAsync(socket),src.Token);
             Console.ReadKey();
             src.Cancel();
        }
        catch
        {
            return;
        }

    }
    public static Task LoopAsync(WebSocket socket){
        byte []buffer=new byte[1024];
        int receivedCount=0;
        while(true){
            WebSocketReceiveResult result=await socket.ReceiveAsync(new ArraySegment<byte>(buffer),CancellationToken.None);
            Console.WriteLine(Encoding.UTF8.GetString(buffer.Take(result.Count)));

        }
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM