Flutter: Build Node WebSocket Server and Connect to it
WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol enables interaction between a web browser (or other client application) and a web server with lower overhead than half-duplex alternatives such as HTTP polling, facilitating real-time data transfer from and to the server.
- Create WSS Server (ws server)
- Connect Flutter application to Socket server
- Run the server on your favourite Server (create a wss server)
1. Create a WSS Server
I’ve created a WebSocket server to run on port 5556 server with the following code.
Let’s run the server locally:
$> node server.js
To test the localhost ws server, go to the websocket.org site https://www.websocket.org/echo.html.
To implement a secure remote solution we would need to create a wss server. wss is secure only because it means “WebSocket protocol over https”. WebSocket protocol itself is not secure. Head over to your favourite server to create a wss within nginx, configure nginx config: “/” server location would give the client access to the web process running at localhost:5555 and “/” wss server location would give the client access to the web socket server running at localhost:5556
Let’s restart our nginx server to allow configs to take effect.
$> sudo service nginx restart
or
$> sudo systemctl restart nginx
Now let’s start the websocket server
$> node server.js
Test wss server:
2. Connect Flutter app
$> flutter create za.co.nanosoft ws_server_example
Let’s modify the main.dart code to connect and listen to our wss server