问题
I am building a messaging system in Django, using web-socket to receive the message.
Here is my tryouts,
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("connected", event)
await self.send({
"type": "websocket.accept"
})
async def websocket_receive(self, event):
print("receive", event)
message = event['text']
obj = await self.create_obj(message=message)
print('Created...')
async def websocket_disconnect(self, event):
print("disconnected", event)
@database_sync_to_async
def create_obj(self, **kwargs):
obj = ChatMessage.objects.create(message=kwargs['message'])
return obj
When I start a client app the web-socket is connected, and i can receive the message and i am able to store into the DB.
connected {'type': 'websocket.connect'}
WebSocket CONNECT /ws/message [192.168.0.101:50148]
After some idle time, the web-socket disconnects automatically,
Application instance <Task pending coro=<SessionMiddlewareInstance.__call__() running at /Users/ajay/Desktop/workspace/projects/python/django/websock/venv/lib/python3.7/site-packages/channels/sessions.py:183> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x10b311510>()]>> for connection <WebSocketProtocol client=['192.168.0.101', 50148] path=b'/ws/message'> took too long to shut down and was killed.
After disconnects, i am not able to receive the message, when i reload the client, web-socket is connected, is there any way to reconnect the we-socket automatically with out reloading the client. I request to guide me some suggestion to achieve this, it will be very helpful for me, Thanks in advance.
回答1:
it seems your client kill the connection.I face the same problem when use as client import websockets".
# part of Client Code in the main while loop
while not self.finished:
try:
self.websocket = await websockets.client.connect(
self.connect_url,
max_size=None,
extra_headers=self.extra_headers
)
.....
# in your`s producer
.......
while True:
# Make sure connection is still live.
pong_waiter = await self.websocket.ping()
await pong_waiter # if you will not await in 10-20 sec connection will close.
来源:https://stackoverflow.com/questions/61037587/django-channels-websocket-reconnect