【问题标题】:Websocket client not connecting to websocket serverWebsocket客户端未连接到Websocket服务器
【发布时间】:2021-05-25 17:59:32
【问题描述】:

我有一个 NET Core 3.1 API,我在其中创建了一个 websocket 服务器并在 API 运行时启动它

API 中的 Program.cs 类:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace aspnetcore_api_server
{
    public class Program
    {
        public class ServerData : WebSocketBehavior
        {
            protected override void OnMessage(MessageEventArgs e)
            {
                Console.WriteLine("WS Status: Received message from client: " + e.Data);
                Send(e.Data);
            }
        }

        public static void Main(string[] args)
        {
            var wssv = new WebSocketServer("ws://127.0.0.1:1234");

            wssv.Start();

            Console.WriteLine("WS Server started on ws://127.0.0.1:1234");

            Console.ReadKey();
            wssv.Stop();
        }
    }
}

然后我有一个 ASP NET MVC Web 应用程序,我试图从它开始与服务器的连接:

using System;
using WebSocketSharp;

namespace aspnet_client
{
    public class WebSocketService
    {
        public WebSocketService()
        {
        }

        public void StartConnection()
        {
            using (WebSocket ws = new WebSocket("ws://127.0.0.1:1234"))
            {
                ws.Connect();
                ws.Send("Hello from client ASP NET web app!");              
            }
        }

        private static void Ws_OnMessage(object sender, MessageEventArgs e)
        {
            Console.WriteLine("Receiveed from the server: " + e.Data);
        }
    }
}

当我尝试通过从客户端执行 ws.Send 将消息发送到服务器时,它会引发错误说明:System.InvalidOperationException: 'The current state of the connection is not Open.'

在 CMD 中,我正在运行命令 netstat -aon,我可以清楚地看到 TCP 端口已打开并正在侦听(见附图)。

我在客户端和服务器端都使用 WebSocketSharp。

有人可以说明我在这里做错了什么或遗漏了什么吗?

【问题讨论】:

    标签: c# asp.net websocket tcp websocket-sharp


    【解决方案1】:

    您可能想要添加服务

    在服务器端

    wssv.AddWebSocketService<ServerData >("/ServerData");

    在客户端,您的 url 将希望在末尾添加 /ServerData

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-27
      • 2013-12-09
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 2016-06-28
      相关资源
      最近更新 更多