[英]nodejs ws comunicate with c#
I want to communicate the C# application with my Node.JS websocket server. 我想将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);
});
});
how to connect the websocket with c#.net and also how to run it 如何将Websocket与c#.net连接以及如何运行它
on(test) event
上(测试)事件
You might wanna look at the following library: https://github.com/sta/websocket-sharp 您可能想看看以下库: https : //github.com/sta/websocket-sharp
Example usage (from the README): 用法示例(自述文件中):
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);
}
}
}
}
This would be a raw implmenetation using the WebSocket
class. 这将是使用
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.