Web socket not working on postman or websocket king
I have a backend project using Django and its for QMS, I want to make two real time notifications : 1-for the client if there is only a ticket ahead 2- is for all clients to see the number of tickets that are in counters here is the asgi file:
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from apps.ticket.routing import websocket_urlpatterns
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qms_api.settings")
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(websocket_urlpatterns)
),
}
)
#and here is the consumers file:
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class TicketConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.group_name = "global_notifications"
# Join the global group
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
async def disconnect(self, close_code):
# Leave the global group
await self.channel_layer.group_discard(self.group_name, self.channel_name)
async def ticket_ahead_notification(self, event):
# Send the ticket ahead notification to the WebSocket
await self.send(text_data=json.dumps(event["data"]))
class TicketInProgressConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.group_name = "tickets_in_progress"
# Join the group
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.group_name, self.channel_name)
async def send_ticket_update(self, event):
await self.send(text_data=json.dumps(event["message"]))
#routing file:
from django.urls import re_path
from apps.ticket.consumers import TicketConsumer,TicketInProgressConsumer
websocket_urlpatterns = [
re_path(r"^tickets/ahead/$", TicketConsumer.as_asgi()),
re_path(r"^tickets/in_progress/$", TicketInProgressConsumer.as_asgi()),
]
#the settings :
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"rest_framework_simplejwt",
"corsheaders",
"django_filters",
"djoser",
"channels",
"daphne",
"user",
"apps.permissions_api",
"apps.contact_us",
"apps.about_us",
"apps.service",
"apps.counter",
"apps.ticket",
]
ASGI_APPLICATION = "qms_api.asgi.application"
# Add a WebSocket backend (e.g., Redis for production)
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [
"redis://default:9UuH504YfwmLBZczZutDZjwCm5A7ZTE6@redis-13656.c259.us-central1-2.gce.redns.redis-cloud.com:13656"
],
"capacity": 1000, # Max messages in a channel
"expiry": 60, # Message expiry time (seconds)
},
},
}
and the URL is : ws://qms-back.khalmagback.xyz:8002/tickets/ahead/ and when I try the postman web socket it says cant connect: Could not connect to ws://qms-back.khalmagback.xyz:8002/tickets/ahead/ 05:10:43 Error: connect ETIMEDOUT 162.0.217.114:8002 Handshake Details Request Method: GET Request Headers Sec-WebSocket-Version: 13 Sec-WebSocket-Key: neXnkUTu/HIAKn5uCuRGvw== Connection: Upgrade Upgrade: websocket Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Host: qms-back.khalmagback.xyz:8002 so I made a script to test the connection :
import websocket
import json
import time
def on_message(ws, message):
try:
data = json.loads(message) # Assuming the server sends JSON
print("Received JSON message from server:", data)
except json.JSONDecodeError:
print("Received non-JSON message:", message)
def on_error(ws, error):
print("Error occurred:", error)
def on_close(ws, close_status_code, close_msg):
print("Connection closed")
def on_open(ws):
print("Connection opened")
while True:
ws.send("Hello from client!") # Send a message to the server
time.sleep(5) # Send a message every 5 seconds
if __name__ == "__main__":
websocket.enableTrace(True)
ws_url = "ws://qms-back.khalmagback.xyz:8002/tickets/ahead/"
ws = websocket.WebSocketApp(ws_url,
on_message=on_message,
on_error=on_error,
on_close=on_close,
on_open=on_open)
try:
ws.run_forever()
except KeyboardInterrupt:
print("Client interrupted. Closing connection...")
ws.close()
and used daphne :
((qms-back.khalmagback.xyz:3.9)) [shergrof@premium700 qms-back.khalmagback.xyz]$ daphne -p 8002 -b 0.0.0.0 qms_api.asgi:application2024-12-02 10:56:51,681 INFO Starting server at tcp:port=8002:interface=0.0.0.02024-12-02 10:56:51,682 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2024-12-02 10:56:51,682 INFO Configuring endpoint tcp:port=8002:interface=0.0.0.0 2024-12-02 10:56:51,683 INFO Listening on TCP address 0.0.0.0:8002 162.0.217.98:58480 - - [02/Dec/2024:10:57:07] "WSCONNECTING /tickets/ahead/" - - 162.0.217.98:58480 - - [02/Dec/2024:10:57:08] "WSCONNECT /tickets/ahead/" - - and run the script and this is the response : ((qms-back.khalmagback.xyz:3.9)) [shergrof@premium700 qms-back.khalmagback.xyz]$ python test_websocket.py --- request header --- GET /tickets/ahead/ HTTP/1.1 Upgrade: websocket Host: qms-back.khalmagback.xyz:8002 Origin: http://qms-back.khalmagback.xyz:8002 Sec-WebSocket-Key: HRQHFUxRqHNEH/AqGwkwYQ== Sec-WebSocket-Version: 13 Connection: Upgrade
--- response header --- HTTP/1.1 101 Switching Protocols Server: daphne Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Accept: Wl7knEh3K6trOvVqneUOll11Ulw=
Websocket connected Connection opened ++Sent raw: b'\x81\x92\xd1\x05\xe9\xd9\x99`\x85\xb5\xbe%\x8f\xab\xbeh\xc9\xba\xbdl\x8c\xb7\xa5$' ++Sent decoded: fin=1 opcode=1 data=b'Hello from client!' ++Sent raw: b'\x81\x92~|\x1c\xde6\x19p\xb2\x11\z\xac\x11\x11<\xbd\x12\x15y\xb0\n]' ++Sent decoded: fin=1 opcode=1 data=b'Hello from client!' ++Sent raw: b'\x81\x92\x9bg\xcc\xf4\xd3\x02\xa0\x98\xf4G\xaa\x86\xf4\n\xec\x97\xf7\x0e\xa9\x9a\xefF' ++Sent decoded: fin=1 opcode=1 data=b'Hello from client!' but still not working on postman web socket or web socket king . can you help me ?