我想与我的Node.JS websocket服务器通信C#应用程序。
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连接以及如何运行
on(测试)事件
答案 0 :(得分:0)
您可能想查看以下库: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);
}
}
}
}
答案 1 :(得分:0)
这是使用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)));
}
}
}
类的原始实现。
{{1}}