How do I know whether to use receive_text
or receive_bytes
?
#52
-
Hi, this is a great library! I've been using this library recently to implement a reverse WebSocket proxy. I establish WebSocket connections with both the client and the target server, acting as an intermediary to pass messages between the two. However, I've encountered an issue: Before receiving messages, how can I determine whether to use server.send_text("Hello World!")
# then
client.receive_bytes() # Boom ! Actually, I know that I can achieve what I want by doing the following: import wsproto
from httpx_ws import WebSocketInvalidTypeReceived, AsyncWebSocketSession
async def receive(self: AsyncWebSocketSession) -> str | bytes:
event = await self.receive()
if isinstance(event, wsproto.events.TextMessage):
return event.data
elif isinstance(event, wsproto.events.BytesMessage):
return event.data
else:
raise WebSocketInvalidTypeReceived(event) But this isn't part of the official API, and I'm not certain whether future updates might cause disruptions. I'm a bit confused. Why does Because I cannot know in advance what type of data will be sent to me from the upstream. Is this due to specific design purposes? If I don't care about the type of message received, is there an officially supported API that allows receiving messages of any type, something like And then I can determine the received data type by using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Well, generally speaking, you know whether your WebSocket sends you a string or bytes; it's part of how it's implemented. So Obviously, for a proxy, you don't know in advance. Thus, the way you show with plain |
Beta Was this translation helpful? Give feedback.
Well, generally speaking, you know whether your WebSocket sends you a string or bytes; it's part of how it's implemented. So
receive_bytes
andreceive_text
are convenient shortcuts.Obviously, for a proxy, you don't know in advance. Thus, the way you show with plain
receive
and check the nature of the message is the way to go. It's part of the API, it's documented: https://frankie567.github.io/httpx-ws/reference/httpx_ws/#httpx_ws.AsyncWebSocketSession.receive