目前,我正试图向我的socket.io服务器提供来自C#客户端的数据。但我不知道如何在服务器上接收消息。
我的服务器代码:
const io = require('socket.io')(9000);
io.on('connection', (socket) => {
console.log('Connected');
}
首先,我不知道必须侦听哪个事件,但是我无法使用以下客户端(使用Websocket)代码将数据发送到服务器:
private void init()
{
// start socket connection
using (var ws = new WebSocket("ws://localhost:9000/socket.io/?EIO=2&transport=websocket"))
{
ws.OnMessage += (sender, e) =>
API.consoleOutput("Message: " + e.Data);
ws.OnError += (sender, e) =>
API.consoleOutput("Error: " + e.Message);
ws.Connect();
ws.Send("server");
}
}
连接工作正常,但如何接收服务器的消息?发送不会触发错误,因此我认为它确实有效。
发布于 2017-03-30 09:08:46
我已经在一个连接到node.js服务器的UWP应用程序中实现了这个功能。基本上,我所做的就是连接到一个看起来像ws://localhost:4200/socket.io/?EIO=3&transport=websocket
的URL
端口号是我们选择的。
设置好后,我将通过下面的代码行连接到node.js socket库。
private async Task ConnectWebsocket() {
websocket = new MessageWebSocket();
Uri server = new Uri(WebSocketURI); //like ws://localhost:4300/socket.io/?EIO=3&transport=websocket
websocket.Control.MessageType = SocketMessageType.Utf8;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Closed += Websocket_Closed;
try {
await websocket.ConnectAsync(server);
isConnected = true;
writer = new DataWriter(websocket.OutputStream);
}
catch ( Exception ex ) // For debugging
{
// Error happened during connect operation.
websocket.Dispose();
websocket = null;
Debug.Log("[SocketIOComponent] " + ex.Message);
if ( ex is COMException ) {
Debug.Log("Send Event to User To tell them we are unable to connect to Pi");
}
return;
}
}
`
此时,"connection“上的套接字io应该会在服务器上启动。
然后,您可以像正常地向它发出事件。除了C#套接字代码不区分不同的通道,所以你必须自己去做。下面是我们是如何做到的(也就是SocketData和SocketIOEvent是我们定义的类)
private void Websocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) {
try {
using ( DataReader reader = args.GetDataReader() ) {
reader.UnicodeEncoding = UnicodeEncoding.Utf8;
try {
string read = reader.ReadString(reader.UnconsumedBufferLength);
//read = Regex.Unescape(read);
SocketData socc = SocketData.ParseFromString(read);
if (socc != null ) {
Debug.Log(socc.ToString());
SocketIOEvent e = new SocketIOEvent(socc.channel, new JSONObject( socc.jsonPayload));
lock ( eventQueueLock ) { eventQueue.Enqueue(e); }
}
}
catch ( Exception ex ) {
Debug.Log(ex.Message);
}
}
} catch (Exception ex ) {
Debug.Log(ex.Message);
}
}
在我们的特定应用程序中,我们不需要向服务器发送消息,因此我没有一个好的答案。
https://stackoverflow.com/questions/41506823
复制