Problem when connecting Django and Flutter websockets | pressku.com

Trending 2 months ago

I'm trying to found a relationship pinch my Django backend and Flutter codification utilizing WebSockets, but unluckily I'm incapable to do so, went done galore articles and videos and everyone is fundamentally doing nan aforesaid without receiving an error.. Please springiness a small push to, I'm kinda caller into this.

First of each I created a caller django app called chat_app (added it into settings.py), wherever I created a caller exemplary of my Messages:

people Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) sender = models.ForeignKey(User, on_delete=models.CASCADE) contented = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content

Then I made my consumers.py

# chat/consumers.py 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 people 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 # Check if nan room exists successful nan database if not await self.room_exists(): await self.close() return # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive connection from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) connection = text_data_json['message'] # Save connection to database Message.objects.create( room=self.unique_id, user=self.scope['user'], content=message ) # Send connection to room group self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': self.scope['user'].username } ) # Receive connection from room group def chat_message(self, event): connection = event['message'] username = event['username'] # Send connection to WebSocket 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 nan routing.py

# The WebSocket URL shape for chat rooms is defined by this code websocket_urlpatterns = [ re_path(r'ws/chat_app/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ]

Then added it into my task URLs:

urlpatterns = [ path('admin/', admin.site.urls), ..., path('ws/', include(websocket_urlpatterns)), ]

And this is really I'm trying to found a relationship successful Flutter, fundamentally it is simply a caller page, wherever I'm passing room information done nan Navigator from nan erstwhile page:

class ChatScreen extends StatefulWidget { const ChatScreen({ Key? key, required this.room, }) : super(key: key); last RoomModelResponse room; @override _ChatScreenState createState() => _ChatScreenState(); } class _ChatScreenState extends State<ChatScreen> { last TextEditingController _controller = TextEditingController(); last List<String> _messages = []; precocious WebSocketChannel _channel; @override void initState() { super.initState(); _channel = IOWebSocketChannel.connect( 'wss://192.168.0.11:8000/ws/chat_app/${widget.room.roomName}/'); // Update nan WebSocket URL pinch your Django server reside and room name _channel.stream.listen((message) { setState(() { _messages.add(message); }); }); }

Outputs:

In nan flutter terminal I get nan pursuing 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 caller 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 nan "3wVCio" is nan unique_id of my room.

I will supply further accusation if need

Update: The latest deliberation I've tried is allowing each root CORS successful my project:

INSTALLED_APPS = [ # different installed apps 'corsheaders', ] CORS_ALLOW_ALL_ORIGINS = True

Unfortunately, nary success..

More
close