I am stuck in this error,I have tried to change many things to fix but still getting error:
(index):42 WebSocket connection to ‘ws://127.0.0.1:8000/ws/chat/user2/’ failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
Here’s below my code:
Client Side:
var roomName = {{ room_name_json }};
var formdata=$("#form");
var input_val=$("#id_messages");
var chatHolder=$("#chat-items");
loc=window.location; // get the addresses
console.log(window.location);
var chatSocket = new WebSocket("ws://" +'127.0.0.1:8000' +
'/ws/chat/' + roomName + '/');
console.log(chatSocket);
// client side receives the message
chatSocket.onmessage = function(e) {
console.log("message",e)
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
chatSocket.onopen = function(e){
console.log("open",e);
formdata.submit(function (event) {
event.preventDefault();
var msgText=input_val.val();
var finalData={
'message':msgText
};
chatSocket.send(JSON.stringify(finalData));
formdata[0].reset()
})
};
chatSocket.onmessage=function(e){
var chatdata=JSON.parse(e.data);
chatHolder.append("<li>"+chatdata.message+ " via "+ chatdata.username +"</li>")
};
chatSocket.onerror= function(e){
console.log("error",e)
};
Consumer.py:
def __init__(self, scope):
super().__init__(scope)
self.chat_room=""
async def websocket_connect(self,event):
me=await self.get_user("user")
other_user="user2" # let pass static value for now for user 2
thread_obj=await self.get_thread(me,other_user)
chat_room=f"thread_{thread_obj.id}"
self.chat_room=chat_room
await self.channel_layer.group_add(
self.chat_room,
self.channel_name
)
await self.send({
"type": "websocket.accept"
})
print(thread_obj)
#await asyncio.sleep(10)
async def websocket_disconnect(self, event):
print("disconnected",event)
async def websocket_receive(self, event):
front_text=event.get('text',None)
if front_text is not None:
load_dict_data=json.loads(front_text)
msg=load_dict_data.get('message')
user=self.scope['user']
username="default"
if user.is_authenticated:
username=user.username
myResponse = {
'message': msg,
'username': username
}
# broadcast the message
await self.channel_layer.group_send(
self.chat_room,
{
"type": "chat_message",
"text":json.dumps(myResponse)
}
)
# message to be sent
async def chat_message(self,event):
await self.send({
"type": "websocket.send",
"text": event['text']
})
@database_sync_to_async
def get_thread(self,user,other_username):
return Thread.objects.get_or_new(user,other_username)[0]
@database_sync_to_async
def get_user(self,username):
Muser=User.objects.get(username=username)
return Muser
Settings.py:
ASGI_APPLICATION = "Frames.routing.application"
CHANNEL_LAYERS={
"default":{
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}
routing.py
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
The socket url where the request sent is correct,but the connections always failed.How can I fix the problem,is there some sort of redis problem?
2
Answers
I was having a similar issue, and it turns out it was due to the bad connection between django and redis. Try using something else for the Channel Layer.
source: https://channels.readthedocs.io/en/latest/topics/channel_layers.html?highlight=channels.layers.InMemoryChannelLayer#in-memory-channel-layer
Warning: Not for Production Use.
If this fixes it, you will at least know that your issue is with redis connection.
(edit): Try upgrading your redis to v5 if haven’t
}
To storage you should it, it worked on me