1

I have server in python and clients in flutter. When I try to send message from one client to another (that message would be sent to the server before ofcourse) it close the stream in flutter for the client that sent the message. For example let's say we have user1 and user2. When user1 sends chat message to user2 the stream of user1 closes and the message doesn't arrive to user2.

import asyncio
import os
import websockets
online_users = []



class User:
    def __init__(self, username, password, email, websocket):
        self.username = username
        self.password = password
        self.email = email
        self.websocket = websocket
        self.logged_in = True


async def send_to_other(dest_user, message):
    print("inbroad")
    for user in online_users:
        print("online " + user.username)
        if user.websocket is None:
            print("NONE")
        print(dest_user + "dest")
        if dest_user == user.username and user.websocket is not None:
            print("here")
            await user.websocket.send(message)


async def handle_message(websocket, path):
    print("here")

    try:
        print("try")
        async for message in websocket:
            print("got message" + message)
            parts = message.split(" ")
            message_type = parts[0]

 
            if message_type == "Chat":
                match_users = []
                src_name = parts[1]
                dst_name = parts[2]
                chat_msg = " ".join(parts[3:])
                print("chat_mnsgg " + chat_msg)
                for match in online_users:
                    if dst_name == match.username:
                        print("adds")
                        match_users.append(match.websocket)
                tasks = [ws.send(f"Chat,{src_name},{chat_msg}") for ws in match_users]
                try:
                    await asyncio.gather(*tasks)
                except Exception as e:
                    print(f"Error sending message: {str(e)}")



    except websockets.exceptions.ConnectionClosedError:
        for user in online_users:
            if user.websocket == websocket:
                print(user.username + " here")
                user.logged_in = False
                user.websocket = None
                break


async def main():
    async with websockets.serve(handle_message, "192.168.0.0", 12345):
        await asyncio.Future()  # run forever


if __name__ == "__main__":
    print("server start")

    asyncio.run(main())

In the flutter code I have the startListening function that I start when the client logs in.

import 'dart:collection';
import 'dart:ui';
import 'package:flutter/material.dart';';
import 'package:web_socket_channel/io.dart';
final channel = IOWebSocketChannel.connect('ws://192.168.0.0:12345');

class MessageHandler {
  final Map<String, Function> messageHandlers = {
    'Match': handleMatch,
    'Chat': handleChat,
    'GetChats': handleGetChat,
  };

  void startListening() {
    print("listening");
    channel.stream.listen((message) {
      print("message received here is $message");
      final messageType = getMessageType(message);
      if (messageHandlers.containsKey(messageType)) {
        messageHandlers[messageType]!(message);
      } else {
        handleUnknownMessage(message);
      }
    }, onDone: () {
      print('Stream closed');
    }, onError: (error) {
      print('Error: $error');
    });
  }

  String getMessageType(String message) {
    final parts = message.split(',');
    return parts.isNotEmpty ? parts[0] : '';
  }


  static void handleChat(String message) {
    print("the message in chats is $message");
    String msgFrom = message.split(",")[1];
    String msgContent = message.split(",")[2];
    if (!chatQueues.containsKey(msgFrom)) {
      chatQueues[msgFrom] = Queue();
    }
    chatQueues[msgFrom]?.add(msgContent);
  }

}

I tried to send it this way also

elif message_type == "Chat":
                match_users = []
                src_name = parts[1]
                dst_name = parts[2]
                chat_msg = " ".join(parts[3:])
                for match in online_users:
                    if dst_name == match.username:
                        match_users.append(match.websocket)
                await asyncio.gather(*[ws.send(f"Chat,{src_name},{chat_msg}") for ws in match_users])

and also with the send_to_other that I showed. Please let me know I something is not clear. (My English is not the best also)

Man3331
  • 21
  • 1

0 Answers0