>[info] 借助这个服务能力来做一个简单的聊天功能(无心跳包支持) >[danger]重点:此处前后端的心跳包都是被注释掉了的,即章节八的关键代码是需要注释掉的,不然会有问题,前端一小会就被踢下线了 ![](https://img.kancloud.cn/a1/53/a153bcdc80565ea27905d47da472241e_1145x264.png) 前端代码:左侧uid2代码: ``` <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Title</title> </head> <body> <script> ws = new WebSocket("ws://123.56.71.69:1234"); ws.onopen = function() { console.log("连接成功"); var uid = '{"id":"uid2","msg":"hello,I`m uid2"}'; ws.send(uid); console.log("给服务端发送一个Json字符串:"+uid); }; ws.onmessage = function(e) { console.log("收到服务端的消息:" + e.data); }; </script> </body> </html> ``` 前端代码:右侧uid3代码: ``` <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Title</title> </head> <body> <script> ws = new WebSocket("ws://123.56.71.69:1234"); ws.onopen = function() { console.log("连接成功"); var uid = '{"id":"uid2","msg":"hello,I`m uid2"}'; ws.send(uid); console.log("给服务端发送一个Json字符串:"+uid); }; ws.onmessage = function(e) { console.log("收到服务端的消息:" + e.data); }; </script> </body> </html> ``` ### 两侧代码仅仅 这段不一样,一个uid2、uid3,这个就可以用一段代码,链接后面跟参数赋值即可 ``` var uid = '{"id":"uid2","msg":"hello,Im uid2"}' ``` ***** 服务端仅仅加了下面代码中的: > sendMessageByUid($data['id'], $data['msg']); ``` $worker->onMessage = function($connection, $data) { global $worker; $connection->lastMessageTime = time(); $data=json_decode($data,true); // 判断当前客户端是否已经验证,既是否设置了uid if(!isset($connection->uid)) { // 没验证的话把第一个包当做uid(这里为了方便演示,没做真正的验证) // $connection->uid = $connection->id; $connection->uid = $data['id']; /* 保存uid到connection的映射,这样可以方便的通过uid查找connection, * 实现针对特定uid推送数据 */ $worker->uidConnections[$connection->uid] = $connection; $connection->send('Link_successful'); // sendMessageByUid($data['id'], $data['msg']); return; }else{ sendMessageByUid($data['id'], $data['msg']); $connection->send('Already_Linked'); } }; ```