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:
-
Node.js installed on your server.
-
The required npm packages installed. You can install them by running:
npm install express moment ws
-
Navigate to the project directory:
cd frontend
-
Install dependencies:
flutter pub get
-
Open the project in your preferred Flutter development environment.
-
Update the WebSocket server URL:
Open the
channelconnect
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:
cd backend
-
Install dependencies:
npm install
-
Start the server:
node server.js
-
The server will be running at
http://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 the
myid
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 the
ws
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 the
webSockets
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 the
webSockets
object.
- Change the port number in the
const port = 8000;
line to the desired port for HTTP connections. - Modify the WebSocket server port in
const wss = new WebSocket.Server({ port: 6060 });
as needed.