Web Socket
WebSockets allow real-time, two-way communication between the client and server
Using WebSockets with the WebApp Package
Overview
WebSockets allow real-time, two-way communication between the client and server. This guide explains how to configure a WebSocket server with the WebApp package in Dart, set up WebSocket routes, and connect a frontend to communicate with the WebSocket server.
Server-Side Configuration
1. Setting Up the Server
To use WebSockets with the WebApp package, configure the server and WebSocket manager as follows:
Explanation:
WaServer
: Creates a new server instance with the given configurations.SocketManager
: Manages WebSocket connections.SocketEvent
: Handles events such as connection, message receipt, and disconnection.server.socketManager?.sendToAll
: Sends a message to all connected clients.socket.send
: Sends a message to the individual socket connection.
2. Configuring WebSocket Routes
Define WebSocket routes and their corresponding actions:
Explanation:
'test'
: Sends headers of the socket request.'close'
: Closes the WebSocket connection.'time'
: Sends the current time.'fa'
: Sends incremented count values every second.'clients'
: Sends a list of all connected clients.'toclient'
: Sends a message to a specific client identified by ID.
Client-Side Configuration
1. Establishing WebSocket Connection
Use JavaScript to connect to the WebSocket server and handle events:
Explanation:
var socket
: Establishes a WebSocket connection to the server.socket.onmessage
: Handles incoming messages from the server based on thepath
.socket.onclose
: Handles WebSocket disconnections.socket.send
: Sends messages to the WebSocket server.initClientList
: Adds event listeners to dynamically created client list elements to send messages to specific clients.
Summary
- Server-Side: Set up WebSocket routes and manage client connections using
SocketManager
andSocketEvent
. - Client-Side: Connect to the WebSocket server using JavaScript, handle incoming messages, and send messages from the client.
This setup allows for real-time communication and interaction between the server and clients, providing a robust framework for building interactive web applications.