我使用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