服務器的環境,建議用bt.cn的一鍵環境javascript
服務端:php
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019\5\23 0023 * Time: 15:12 */ class Server{ public function __construct() { $sw = new swoole_websocket_server('0.0.0.0',9501); $sw->on('open',function($server, $request){ echo '客戶端已經鏈接'.PHP_EOL; }); $sw->on('message',function(swoole_websocket_server $server, $frame){ echo PHP_EOL. '服務端已經收到消息'; echo PHP_EOL. "客戶端id: " .$frame->fd ; //客戶端id echo PHP_EOL. "接收的消息: " .$frame->data ; //接收的數據 $server->push($frame->fd,"服務把你的信息原封不動的給你了-->".$frame->data); }); $sw->on('close',function($ser, $fd){ echo '鏈接已經關閉'; }); $sw->start(); } } new Server();
客戶端:css
<html> <head> <title>demo</title> <script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script> </head> <body> <input type="text" id="content"> <input type="button" value="send" id="send"> <script type="text/javascript"> var ws = new WebSocket("ws://192.168.56.101:9501"); ws.onopen = function(){ console.log("握手成功"); } ws.onmessage = function(e){ console.log("message:" + e.data); } ws.onerror = function(){ console.log("error"); } $("#send").click(function(){ content = $("#content").val(); console.log(content); ws.send(content); }) </script> </body> </html>
結果:html