Flutter Chat App with WebSocket This Flutter application and Node.js backend server demonstrate a simple real-time chat application using WebSocket communication.
Real-time messaging using WebSocket. Simple and intuitive user interface. Visual indication of connection status in the app bar. Ability to send and receive messages. Before running the app, make sure you have the following:
Flutter installed on your development environment. A WebSocket server running. You can use a local server for testing. Before running the backend server, ensure you have the following:
Navigate to the project directory:
Install dependencies:
Open the project in your preferred Flutter development environment.
Update the WebSocket server URL:
Open thechannelconnect
method in theChatPageState
class, and modify the WebSocket server URL:
channel= IOWebSocketChannel .connect ("ws://your-server-ip:your-server-port/$myid " ); Run the app on two devices or simulators/emulators.
Navigate to the project directory:
Install dependencies:
Start the server:
The server will be running athttp://localhost:8000
. You can customize the port in the code.
Launch the Flutter app on two devices or simulators/emulators.
Each instance of the app can act as a sender or receiver. Update themyid
andreceiverid
variables in theChatPageState
class accordingly.
Messages sent from one instance will be received by the other, creating a chat experience.
ChatPage
: The main widget for the chat page.ChatPageState
: Manages the state of theChatPage
widget, including WebSocket connection and message handling.MessageData
: Represents the model for chat messages.The WebSocket server is initiated using thews
library on port 6060. It listens for incoming connections and assigns a unique user ID based on the URL path. When a WebSocket connection is established, the server logs the user ID and adds the connection to thewebSockets
object. The server listens for incoming messages from clients. It validates the message format and authentication key. If authentication is successful and the message is of the "send" type, it forwards the message to the recipient's WebSocket connection. When a WebSocket connection is closed, the server removes the corresponding entry from thewebSockets
object. Change the port number in theconst port = 8000;
line to the desired port for HTTP connections. Modify the WebSocket server port inconst wss = new WebSocket.Server({ port: 6060 });
as needed.