C# & JS WebSocket 某些用户无法连接到服务器

C# & JS WebSocket Some users can't connect to server

本文关键字:用户 连接 服务器 amp JS WebSocket      更新时间:2023-09-26

我现在遇到了一个非常大的问题:我有一个服务器,用户可以在其中使用Alchemy库连接和发送和接收用C#编写的消息,但现在我从一些用户那里得到了一些报告,他们无法连接到websocket服务器。在服务器日志中,它们会自动断开连接,而不是连接。

下面是 C# 代码:

internal static bool Init(int bindPort, int maxConnections)
    {
        _Port = bindPort;
        _maxConnections = maxConnections;
        _activeConnections = new HashSet<int>();

        try
        {
            var aServer = new WebSocketServer(_Port, IPAddress.Any)
            {
                OnReceive = OnReceive,
                OnSend = OnSend,
                OnConnected = OnConnect,
                OnDisconnect = OnDisconnect,
                TimeOut = new TimeSpan(0, 5, 0)
            };
            aServer.Start();
            Console.WriteLine(" [] WebSockets port: " + _Port + ".");
            return true;
        }
        catch
        {
            Console.WriteLine(" WebSocket konnte nicht geladen werden");
            return false;
        }
    }
    public static void SendAll(string data)
    {
        foreach(UserContext Kubbo in OnlineUsers.Keys)
        {
            Kubbo.Send(data);
        }
    }
    private static void OnConnect(UserContext context)
    {
        try
        {
            int connectionID = 0;
            for (int i = 1; i < _maxConnections; i++)
            {
                if (_activeConnections.Contains(i) == false)
                {
                    connectionID = i;
                    break;
                }
            }
            if (connectionID > 0)
            {
                Console.WriteLine("[" + connectionID + "] Verbindung " + context.ClientAddress);
                context.Send("A");
                _activeConnections.Add(connectionID);
                _acceptedConnections++;
                var me = new User { Context = context };
                OnlineUsers.Add(context, context.ClientAddress.ToString());
            }
        }
        catch
        {
        }
    }
    internal static void OnDisconnect(UserContext context)
    {
        try
        {
            OnlineUsers.Remove((UserContext)context);
            Console.WriteLine("[] Verbindung wurde geschloßen");
        }
        catch
        {
            Console.WriteLine("{}");
        }
    }

Javascript代码(使用JavaScript中实现的普通Socket API非常简单):

 var ws = new WebSocket("ws://localhost:38819/");
 ws.onopen = function()
 {
    ws.send("A");
    alert("Connection sucessfully opened");
 };
  ws.onclose = function()
 { 
    alert("Connection is closed..."); 
 };

服务器在什么操作系统上运行?例如,Windows 7 旗舰版的默认值为 20 个并发连接。