>[info] 借助這個服務能力來做一個簡單的聊天功能(無心跳包支持)
>[danger]重點:此處前后端的心跳包都是被注釋掉了的,即章節八的關鍵代碼是需要注釋掉的,不然會有問題,前端一小會就被踢下線了

前端代碼:左側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');
}
};
```