I. Basic overview of Websocket
WebSocket protocol is a new network protocol based on TCP. It realizes full-duplex communication between browser and server - allowing server to send information to client actively.
Why do we need WebSocket?
Defect: HTTP communication can only be initiated by the client
WebSocket features:
- Based on TCP Protocol
- Performance overhead, low communication efficiency
- Client can communicate with any server
- Protocol identifier ws wss
- Persistent Network Communication Protocol
2. Code Implementation
websocket server
ws_server.php
<?php //Create websocket server object and listen on port 0.0.0.0:80 $ws = new swoole_websocket_server("0.0.0.0", 80); //Listen for WebSocket Connection Open Events $ws->on('open', function ($ws, $request) { var_dump($request->fd, $request->get, $request->server); $ws->push($request->fd, "hello, welcome\n"); }); //Listening for WebSocket message events $ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "server: {$frame->data}"); }); //Listening for WebSocket Connection Closure Events $ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; }); $ws->start();
Because we are in the docker container, we use port 80 so that we can access the service in the host browser by mapping the ports before the host passes through.
Port View of Host Container Mapping:
➜ ~ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5ee6bfcc1310 7698f "/bin/bash" 46 hours ago Up 30 hours 0.0.0.0:2221->22/tcp, 0.0.0.0:8880->80/tcp confident_jones
Client static page
Static page path: / work/study/code/swoole/demo/static
ws_client.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebSocket TEST</title> </head> <body> <h1>Swoole-TEST</h1> <script> var wsUrl = "ws://0.0.0.0:8880"; var websocket = new WebSocket(wsUrl); // Instantiating onopen objects websocket.onpen = function(evt){ console.log("connected-swoole-success") } // Instantiate onmessage websocket.onmessage = function(evt){ console.log("ws-server-return-data"+evt.data) } // Instantiate onclose websocket.onclose = function(evt){ console.log("close") } // onerror websocket.onerror = function (evt) { console.log("error:" + evt.data) } </script> </body> </html>
Host browser access: