workerman下载地址:https://www.workerman.net/
-》
1,start.php workerman服务器
2,song.html发送页面
3,wor.html接收页面
4,php start.php start 连接workerman服务
5,telnet 127.0.0.1 2345 测试是否连接成功
start.php :
<?php
use Workerman\Worker;
require_once '../Autoloader.php';
$global_uid = 0;
当客户端连上来时分配uid,并保存连接,并通知所有客户端
function handle_connection($connection){
global $text_worker,$global_uid;
// 为这个连接分配一个uid
$connection->uid = ++$global_uid;
}
// 当客户端发送消息过来时,转发给所有人
function handle_message($connection,$data){
global $text_worker;
foreach ($text_worker->connections as $conn){
$conn->send("user[{$connection->uid}] said: '是的'");
}
}
// 当客户端断开时,广播给所有客户端
function handle_close($connection){
global $text_worker;
foreach ($text_worker->connections as $conn){
$conn->send("user[{$connection->uid}] logout");
}
}
// 创建一个文本协议的Worker监听2347接口
$text_worker = new Worker('websocket://0.0.0.0:2345');
// 只启动1个进程,这样方便客户端之间传输数据
$text_worker->count = 1;
$text_worker->onConnect='handle_connection';
$text_worker->onMessage='handle_message';
$text_worker->onClose = 'handle_close';
Worker::runAll();
song.html :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
您好:
</body>
</html>
<script>
// 假设服务端ip为127.0.0.1,测试时请改成实际服务端ip
ws = new WebSocket("ws://127.0.0.1:2345");
ws.onopen = function(e) {
// alert("收到服务端的消息:" + e.data);
ws.send('啦啦啦啦');
};
</script>
wor.html :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
我很好:
</body>
</html>
<script>
// 假设服务端ip为127.0.0.1,测试时请改成实际服务端ip
ws = new WebSocket("ws://127.0.0.1:2345");
ws.onmessage = function(e) {
alert("收到服务端的消息:" + e.data);
};
</script>
通过start.php内IP地址连接