繁体   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