我正在尝试将socket.io服务器中的数据解析到使用WebSocketSharp的C#应用程序中。连接,断开连接并将数据发送到服务器的工作正常,我似乎无法弄清楚如何从服务器接收数据。如果有人可以给我小费,那就太好了。
C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
namespace TestNode
{
class Program
{
static void Main(string[] args)
{
string str = "42[\"test\", { \"type\":\"s\",\"key\":\"1\",\"room\":\"eq\"}]";
using (var ws = new WebSocket("ws://127.0.0.1:3000/socket.io/?EIO=2&transport=websocket"))
{
ws.OnOpen += (sender, e) =>
{
Console.WriteLine("Connected.");
};
ws.OnClose += (sender, e) =>
{
Console.WriteLine("Connection closed.");
Console.ReadLine();
};
ws.OnMessage += (sender, e) =>
{
Console.WriteLine(e.Data);
Console.ReadKey();
};
ws.Connect();
ws.Send(str);
Console.ReadKey(true);
}
}
}
}
输出:
已连接。
0 {“ sid”:“ 8IqgbzY-untT8dcLAAAA”,“升级”:[],“ pingInterval”:25000,“ pingTimeout”:5000}
连接已关闭。
服务器代码:
var express = require('express');
var app = express();
var server = app.listen(3000);
var socket = require('socket.io');
var io = socket(server);
users = [];
connections = [];
console.log('Server is running');
io.on('connection', function(socket){
connections.push(socket);
console.log('Connected: ' + socket.id);
socket.on('disconnect', function() {
console.log('Disconnected.');
});
socket.on('test', function() {
console.log('Succesfull');
var car = {
type: "Fiat",
model: "500",
color: "white"
};
socket.emit("test", car);
});
});
**输出:**
服务器正在运行
已连接:8IqgbzY-untT8dcLAAAA
成功
已断开连接。