Issue
I COMMUNICATE BETWEEN ASP NET C# AND PYTHON using a websocket, or more specifically, I use a signalR library in both cases. I'm trying to get my server to respond in some way when a Python client sends a message. nothing helps for now. anyone had this problem?
it is enough that after the client sends the message, the function in the hub named SendGemstoneDetailMessage will work.that's what I mean
Python Code:
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# code:
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");
}
}
Logs from client in python:
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
Solution
# Send a message after connection
# self.hub_connection.send("SendGemstoneDetailMessage", ["dwdw"])
self.hub_connection.send("SendGemstoneDetailMessage", [["dwdw"]])
You are missing []
in your frontend code, since you are using SendGemstoneDetailMessage(List<string> messag)
, you should use [["dwdw"]]
.
If you want send string messagem like SendGemstoneDetailMessage(string messag)
, and ["dwdw"]
should work.
Answered By - Jason Pan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.