PHP 用于发送数据的棘轮套接字客户端

PHP Ratchet socket client for sending data

我正在使用 PHP 棘轮套接字服务器,我想通过 php 客户端向该套接字服务器发送数据。我的套接字服务器在 HTML 5 个网络套接字上运行良好,但 php 客户端无法正常工作。这是我的代码

$host    = "localhost";
$port    = 9000;
$message = "Hello Server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);

当我 运行 这段代码没有任何反应...有什么帮助吗?

您可能不是在寻找 PHP websockets 客户端,而是在寻找推送服务器。 http://socketo.me/docs/push

在 socketo.me 的网站上解释了如何设置。 给你一个简短的总结:

推送服务器是您的应用程序逻辑和 websocket 本身之间的层。 这将使您可以将请求发送到推送服务器,然后将请求发送到消息所针对的 websocket 的客户端。

如果您需要任何进一步的解释,请告诉我。

这篇文章来晚了,但对于希望澄清这些概念的人可能会有所帮助。

socket_create()socket_connect() 是 PHP 核心函数,编写用于 TCPUDP 协议,但不适用于 webSocket 连接 (ws://uri:port)。

对于本题的项目,最好是使用@mitchken提到的现成的websocket客户端包(ratchet/pawl、amphp/websocket-client等)

我个人使用过 amphp,它工作得非常好,特别是如果您需要更新特定 user/group 的 UI 以响应后端发生的 event/notification ,通过使用 PHP websocket 客户端发送消息并在 websocket 服务器适配器 class.

的 onMessage() 事件中将消息重定向到目标用户