【发布时间】:2014-03-04 10:51:42
【问题描述】:
我正在使用 PHP-Websocket 开发一个小项目。
服务器端正在使用这个https://github.com/ghedipunk/PHP-Websockets运行
服务器端:
require "PHP-Websockets/websockets.php";
class Server extends WebSocketServer
{
private $_connecting = 'Connecting..';
private $_welcome = 'SOCKET SERVER!';
protected function connected($user)
{
// Send welcome message to user when connected
}
protected function process($user, $message)
{
// data sent from client
$json = json_decode($message);
//prepare data response to client
$response = json_encode(array('type'=>'notify', 'message'=>'Client'.$user->id.' has sent a request.'));
$this->send($user, $response);
}
protected function closed($user)
{
// Alert on server
echo "User $user->id has closed the connection".PHP_EOL;
}
public function __destruct()
{
echo "Server Closed!".PHP_EOL;
}
}
$addr = 'localhost';
$port = '2207';
$server = new Server($addr, $port);
$server->run();
客户端:
<script>
var uri = "ws://localhost:2207";
function socket_connect(){
socket = new WebSocket(uri);
if(!socket || socket == undefined) return false;
socket.onopen = function(){
console.log('Connected to Server!');
}
socket.onerror = function(){
console.log('Connection Failed!');
}
socket.onclose = function(){
socket_log('Connection Closed! ')
}
socket.onmessage = function(e){
//var response_data = e.data;
var msg = JSON.parse(e.data); //PHP sends Json data to client
console.log(msg.message);
var new_response = '<li>'+msg.message+'</li>;
$('#response').append(new_response);
}
}
function send_data_to_server(data){
if(!socket || socket == undefined) return false;
socket.send(JSON.stringify(data));
}
$(document).ready(function(){
socket_connect();
$('#send_request').click(function(){
send_data_to_server({message: 'Message sent from Client'});
});
});
</script>
<input type="button" id="send_request" value="Send Request to Server" />
<ul id="responses"></ul>
上面的代码一切正常。
当 Client1 向 Server 发送请求时,Server 会立即响应他。但是其他客户端看不到响应消息。
所以我想让它更进一步:当客户端向服务器发送请求时,服务器将响应 ALL 客户端,以便所有客户端都能看到消息。
我该怎么做?
提前感谢&&对不起我的英语不好!
【问题讨论】:
-
根据this guide,可能已经有一个
WebSocketServer::$users可遍历变量foreach。 -
我知道这是旧的,但是 ghedipunk api 是如何为您工作的?我现在正在考虑将它用于基本的 Web 套接字应用程序。有没有人在这个线程上找到了更好的?
标签: php websocket phpwebsocket