使用C#客户端连接到socket.io,但加入/使用房间

huangapple go评论90阅读模式
英文:

Connecting to socket.io using C# client, but using/joining room

问题

我正在使用 Node 和 React,使用 socket.io 创建房间没有任何问题。

在我的服务器端,我有以下代码段:

socket.on('connection', socket => {
  console.log('user connected');
  
  let room = socket.handshake['query']['r_var'];
  socket.join(room);
  console.log('user joined room #' + room);
});

这是我从客户端连接的方式:

import openSocket from 'socket.io-client';
openSocket(`${readerUrl}:${wsPort}`, {
  query: 'r_var=dynamic_room'
})

我需要在 C# 中实现相同的功能,尽管我找到了一些 C# 的示例,但没有一个使用房间。有人有示例吗?

非常感谢!

英文:

I'm using socket.io with rooms without any problem with Node and React.

In my server side, I've this piece if code:

socket.on('connection', socket => {
  console.log('user connected');

  let room = socket.handshake['query']['r_var'];
  socket.join(room);
  console.log('user joined room #' + room);
});

And this is how I connecting from client side:

import openSocket from 'socket.io-client';
openSocket(`${readerUrl}:${wsPort}`, {
              query: 'r_var=dynamic_room'
            })

I need to do the same, but with C#. Although I found several examples for C#, none uses rooms. Anybody have some example?

Thanks so much!

答案1

得分: 1

我自己解决了问题,并分享解决方案,供需要的人使用。

使用的包是https://github.com/Quobject/SocketIoClientDotNet。它已经过时,但功能非常好,而且经常更新。

要传递查询(用于加入socket.io房间),需要使用类型为“Dictionary”的变量。

var query = new Dictionary<string, string>();
query.Add("room", "test");

var options = new IO.Options();
options.Query = query;

var Socket = IO.Socket("http://xxx.xxx.xxx.xxx:3001", options);

如你所见,我不是C#程序员,可能可以改进代码。

英文:

I solved it myself and I share the solution for who need it too.

The used package was https://github.com/Quobject/SocketIoClientDotNet. It's deprecated but work very well and it's pretty updated.

To pass a query (used to join rooms on socket.io), you need to use a var of type "Dictionary".

var query = new Dictionary&lt;string, string&gt;();
query.Add(&quot;room&quot;, &quot;test&quot;);
    
var options = new IO.Options();
options.Query = query;

var Socket = IO.Socket(&quot;http://xxx.xxx.xxx.xxx:3001&quot;, options);

As you can see I'm not C# programmer, it's probably that you can improve the code.

huangapple
  • 本文由 发表于 2020年1月3日 23:18:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定