我使用WebSocket在ASP.Net C#和Python之间通信,或者更具体地说,在这两种情况下我都使用SignalR库.我正在try 让我的服务器在Python客户端发送消息时以某种方式响应.就目前而言,没有任何帮助. 有人遇到过这个问题吗?

在客户端发送消息后,集线器中名为SendGemstoneDetailMessage的函数就足够了.这就是我的意思

Python代码:

import logging

from signalrcore.hub_connection_builder import HubConnectionBuilder
import asyncio

class SignalRClient:
    def __init__(self):
        self.hub_connection = None

    def connect(self):
        try:
            self.hub_connection = HubConnectionBuilder() \
                        .configure_logging(logging.DEBUG) \
                        .with_automatic_reconnect({
                        "type": "raw",
                        "keep_alive_interval": 10,
                        "reconnect_interval": 5,
                        "max_attempts": 5
                    }) \
                .with_url("https://localhost:7294/WebSocketMessageHub", options={"verify_ssl": False}) \
                .build()

            self.hub_connection.on("ReceiveMessage", self.receive_message) 

            self.hub_connection.start()
            self.hub_connection.on_open(lambda: print("connection opened and handshake received ready to send messages"))
            self.hub_connection.on_close(lambda: print("connection closed"))
            self.hub_connection.on_error(lambda data: print(f"An exception was thrown closed{data.error}"))

            print("Connected to SignalR Hub")

            # Send a message after connection
            self.hub_connection.send("SendGemstoneDetailMessage", ["dwdw"])
        except Exception as e:
            print(f"Failed to connect to the server: {e}")

    def receive_message(self, *args, **kwargs):
        # Handle received messages
        print(f"ITS MEE: {args}")

    async def listen_forever(self):
            while True:
                await asyncio.sleep(1)  # not blocking threads


async def main():
    signalr_client = SignalRClient()
    signalr_client.connect()
    await signalr_client.listen_forever()
        



if __name__ == "__main__":

    asyncio.run(main())

C#代码:

public class WebSocketHub : Hub
{
    private readonly IWebSocketService _webSocketService;

    public WebSocketHub(IWebSocketService webSocketService)
    {

        _webSocketService = webSocketService;
    }


    public override Task OnConnectedAsync()
    {
        _webSocketService.ConnectAdmin(Context);

     
        return base.OnConnectedAsync();
    }

    public async Task SendGemstoneDetailMessage(List<string> messag)
    {

        Console.WriteLine("HELLO");
    }
}

来自客户端的PYTHON日志(log):

2023-12-18 18:41:25,857 - SignalRCoreClient - DEBUG - Handler registered started ReceiveMessage
2023-12-18 18:41:25,857 - SignalRCoreClient - DEBUG - Connection started
2023-12-18 18:41:25,857 - SignalRCoreClient - DEBUG - Negotiate url:https://localhost:7294/WebSocketMessageHub/negotiate
/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py:1100: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
Connected to SignalR Hub
2023-12-18 18:41:27,021 - SignalRCoreClient - DEBUG - Response status code200
2023-12-18 18:41:27,021 - SignalRCoreClient - DEBUG - start url:wss://localhost:7294/WebSocketMessageHub?id=0JER4PQd5JeF97061acC2Q
2023-12-18 18:41:27,021 - SignalRCoreClient - DEBUG - Sending message InvocationMessage: invocation_id 6c1a818b-9aae-4d95-b08b-85c2c08606fc, target SendGemstoneDetailMessage, arguments ['dwdw']
2023-12-18 18:41:27,021 - SignalRCoreClient - DEBUG - {"type": 1, "headers": {}, "target": "SendGemstoneDetailMessage", "arguments": ["dwdw"], "invocationId": "6c1a818b-9aae-4d95-b08b-85c2c08606fc"}
2023-12-18 18:41:27,021 - SignalRCoreClient - WARNING - Connection closed socket is already closed.
2023-12-18 18:41:27,022 - SignalRCoreClient - INFO - on_reconnect not defined
2023-12-18 18:41:27,022 - SignalRCoreClient - DEBUG - Negotiate url:https://localhost:7294/WebSocketMessageHub/negotiate?id=0JER4PQd5JeF97061acC2Q
/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py:1100: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
2023-12-18 18:41:27,541 - SignalRCoreClient - DEBUG - Response status code200
2023-12-18 18:41:27,541 - SignalRCoreClient - DEBUG - start url:wss://localhost:7294/WebSocketMessageHub?id=cQ-mlq9xR3QcJLxuREJVyw
2023-12-18 18:41:27,738 - SignalRCoreClient - DEBUG - -- web socket open --
2023-12-18 18:41:27,738 - SignalRCoreClient - DEBUG - Sending message <signalrcore.messages.handshake.request.HandshakeRequestMessage object at 0x103513bd0>
2023-12-18 18:41:27,738 - SignalRCoreClient - DEBUG - {"protocol": "json", "version": 1}
2023-12-18 18:41:28,272 - SignalRCoreClient - DEBUG - -- web socket open --
2023-12-18 18:41:28,272 - SignalRCoreClient - DEBUG - Sending message <signalrcore.messages.handshake.request.HandshakeRequestMessage object at 0x1058e3b50>
2023-12-18 18:41:28,272 - SignalRCoreClient - DEBUG - {"protocol": "json", "version": 1}
2023-12-18 18:41:28,280 - SignalRCoreClient - DEBUG - Message received{}
2023-12-18 18:41:28,280 - SignalRCoreClient - DEBUG - Evaluating handshake {}
connection opened and handshake received ready to send messages
2023-12-18 18:41:31,695 - SignalRCoreClient - DEBUG - Message received{"type":7,"error":"Connection closed with an error.","allowReconnect":true}
2023-12-18 18:41:31,695 - SignalRCoreClient - DEBUG - Raw message incomming: 
2023-12-18 18:41:31,695 - SignalRCoreClient - DEBUG - {"type":7,"error":"Connection closed with an error.","allowReconnect":true}
2023-12-18 18:41:31,695 - SignalRCoreClient - INFO - Close message received from server
2023-12-18 18:41:31,695 - SignalRCoreClient - DEBUG - Connection stop

推荐答案

# Send a message after connection
# self.hub_connection.send("SendGemstoneDetailMessage", ["dwdw"])

self.hub_connection.send("SendGemstoneDetailMessage", [["dwdw"]])

您的前端代码中缺少[],因为您使用的是SendGemstoneDetailMessage(List<string> messag),所以您应该使用[["dwdw"]].

如果您想发送类似SendGemstoneDetailMessage(string messag)["dwdw"]的字符串消息,应该可以.

enter image description here

Python相关问答推荐

带有计数值的Pandas数据帧

是什么导致对Python脚本的jQuery Ajax调用引发500错误?

指示组内的rejected_time是否在creation_timestamp后5分钟内

如何用symy更新分段函数

如何通过多2多字段过滤查询集

DataFrame groupby函数从列返回数组而不是值

Pandas实际上如何对基于自定义的索引(integer和非integer)执行索引

Pandas 滚动最接近的价值

有症状地 destruct 了Python中的regex?

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

如何在polars(pythonapi)中解构嵌套 struct ?

如何获取numpy数组的特定索引值?

ODE集成中如何终止solve_ivp的无限运行

OR—Tools中CP—SAT求解器的IntVar设置值

实现自定义QWidgets作为QTimeEdit的弹出窗口

在Python中调用变量(特别是Tkinter)

使用Python从rotowire中抓取MLB每日阵容

处理具有多个独立头的CSV文件

将标签移动到matplotlib饼图中楔形块的开始处

如何使用OpenGL使球体遵循Python中的八样路径?