如何在.net上的WebSocket中显示已连接的客户端列表

vnjpjtjt  于 2023-06-23  发布在  .NET
关注(0)|答案(1)|浏览(141)

我在. net中用控制台应用程序制作了websocket应用程序。
Program.cs:

using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fleck;

namespace WebSocketConsole
{
    public class Program
    {
        static void Main(string[] args)
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://0.0.0.0:7080");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("İstemci bağlantısı başarılı!");
                    allSockets.Add(socket);
                    Console.WriteLine("Mevcut istemci sayısı: " + allSockets.ToList().Count);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("İstemci bağlantısı koptu!");
                    allSockets.Remove(socket);
                    Console.WriteLine("Mevcut istemci sayısı: " + allSockets.ToList().Count);
                };
                // Mesaj Teslim Alındığında
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    allSockets.ToList().ForEach(s => s.Send(message));
                };
            });

            //giriş mesajını oku
            var input = Console.ReadLine();
            //When the message is not "exit", enter an infinite loop
            while (input != "exit")
            {
                //Tüm soket istemcilerini dolaş ve her istemciye mesaj gönder
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
    }
}

htmlpage.html:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <title></title>
</head>
<body>
 <div>Mesaj Gönder:</div>
 <input type="text" id="msgContent" />
 <input type="button" value="Gönder" onclick="CHAT.chat()" />
 <div>Gönderilen Mesaj:</div>
 <div id="receiveMsg" style="background-color: gainsboro;"></div>
 <script type="application/javascript">

          window.CHAT = {
              socket: null,
              init: function() {
                  if (window. WebSocket) {
                      CHAT.socket = new WebSocket("ws://127.0.0.1:7080/ws");//websocket server address and port
                      CHAT.socket.onopen = function() {
                          console.log("Bağlantı başarıyla kuruldu...");
                      },
                      CHAT.socket.onclose = function() {
                          console.log("Bağlantı kesildi...");
                      },
                      CHAT.socket.onerror = function() {
                          console.log("Bir hata oluştu...");
                      },
                      CHAT.socket.onmessage = function(e) {
                          console.log("Received message: " + e.data);
                          var receiveMsg = document. getElementById("receiveMsg");
                          var html = receiveMsg. innerHTML;
                          receiveMsg.innerHTML = html + "<br/>" + e.data;
                      }
                  } else {
                      alert("Bu taryacı websocket protokolünü desteklemiyor...");
                  }
              },
              chat: function() {
                  var msg = document. getElementById("msgContent");
                  CHAT.socket.send(msg.value);

              }
          };

          CHAT.init();

 </script>

我如何显示连接的客户端列表与下拉列表?在哪里可以列出已连接的客户端。我试着在网上搜索并尝试了一下,但我无法弄清楚。
此外,我们可以按设备类型划分客户端吗?例如android,ios,windows,macOs,ubuntu

tvmytwxo

tvmytwxo1#

您需要使用Winforms或其他带有下拉列表的项目类型来创建服务器。下面是使用Winforms创建服务器的示例:
1.创建一个windows窗体应用程序项目(我使用的是.netframework版本):

1.拉取组合框

1.代码如下:

namespace WebSocketCombox
{
 public partial class Form1 : Form
 {

     public void StartWebSocketServer()
     {
         Task.Run(() =>
         {
             FleckLog.Level = LogLevel.Debug;
             var allSockets = new List<IWebSocketConnection>();
             var server = new WebSocketServer("ws://0.0.0.0:7080");
             server.Start(socket =>
             {
                 string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                 socket.OnOpen = () =>
                 {
                     allSockets.Add(socket);
                     comboBox1.Items.Add(clientUrl);

                 };
                 socket.OnClose = () =>
                 {
                     allSockets.Remove(socket);
                     comboBox1.Items.Remove(clientUrl);
                 };
                 // When a message is received
                 socket.OnMessage = message =>
                 {
                     allSockets.ToList().ForEach(s => s.Send(message));
                 };
             });
         });
     }

     public  Form1()
     {
         InitializeComponent();
         CheckForIllegalCrossThreadCalls = false;
         StartWebSocketServer();
     }
 }

}
1.启动服务器项目。
1.启动客户端项目
这样,你会发现客户端的IP地址和端口号被添加到了ComboBox中

如果你想让它显示设备类型,你可以参考jdweng的意见。

相关问题