I'm trying to establish a connection with my Django backend and Flutter code using WebSockets, but unfortunately I'm unable to do so, went through many articles and videos and everyone is basically doing the same without receiving an error.. Please give a little push to, I'm kinda new into this.
What I have tried:
First of all I created a new django app called 'chat_app' (added it into settings.py), where I created a new model of my Messages:
class Message(models.Model):
room = models.ForeignKey(Room, on_delete=models.CASCADE)
sender = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.content
Then I made my consumers.py (here I'm a little bit confused, isn't it better to refer to my room unique_id instead of name, since the ID is unique and not the name in my case? Decided to stick with the tutorial.)
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
from .models import Message
from room_app.models import Room
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.unique_id = self.scope['url_route']['kwargs']['unique_id']
self.room_group_name = 'chat_%s' % self.unique_id
if not await self.room_exists():
await self.close()
return
self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
Message.objects.create(
room=self.unique_id,
user=self.scope['user'],
content=message
)
self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
'username': self.scope['user'].username
}
)
def chat_message(self, event):
message = event['message']
username = event['username']
self.send(text_data=json.dumps({
'message': message,
'username': username
}))
@sync_to_async
def room_exists(self):
return Room.objects.filter(unique_id=self.unique_id).exists()
Done the routing.py
websocket_urlpatterns = [
re_path(r'ws/chat_app/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()),
]
Then added it into my project URLs:
urlpatterns = [
path('admin/', admin.site.urls),
...,
path('ws/', include(websocket_urlpatterns)),
]
And this is how I'm trying to establish a connection in Flutter, basically it is a new page, where I'm passing room data through the Navigator from the previous page:
class ChatScreen extends StatefulWidget {
const ChatScreen({
Key? key,
required this.room,
}) : super(key: key);
final RoomModelResponse room;
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _controller = TextEditingController();
final List<String> _messages = [];
late WebSocketChannel _channel;
@override
void initState() {
super.initState();
_channel = IOWebSocketChannel.connect(
'wss://192.168.0.11:8000/ws/chat_app/${widget.room.roomName}/');
_channel.stream.listen((message) {
setState(() {
_messages.add(message);
});
});
}
Outputs:
In the flutter terminal I get the following message:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'http://192.168.0.11:8000/ws/chat_app/3wVCio/#' was not upgraded to websocket
#0 new IOWebSocketChannel._withoutSocket.<anonymous closure> (package:web_socket_channel/io.dart:119:24)
#1 Stream.handleError.<anonymous closure> (dart:async/stream.dart:931:16)
#2 _HandleErrorStream._handleError (dart:async/stream_pipe.dart:269:17)
#3 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:157:13)
#4 _RootZone.runBinaryGuarded (dart:async/zone.dart:1606:10)
#5 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
#6 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:7)
#7 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:280:7)
#8 _SyncStreamControllerDispatch._sendError (dart:async/stream_controller.dart:788:19)
#9 <…>
Django:
Not Found: /ws/chat_app/3wVCio/
[15/Feb/2024 16:46:19] "GET /ws/chat_app/3wVCio/ HTTP/1.1" 404 4379
Where the "3wVCio" is the unique_id of my room.
I will provide additional information if need
Update: The latest think I've tried is allowing all origin CORS in my project:
INSTALLED_APPS = [
# other installed apps
'corsheaders',
]
CORS_ALLOW_ALL_ORIGINS = True
Unfortunately, no success..