简体   繁体   中英

PHP Ratchet socket client for sending data

I am using a PHP Ratchet Socket server and I want to send data to this socket server via a php client. My socket server is working well with HTML 5 web sockets but php client isn't working. Here is my code

$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);

when I run this code nothing happens... Any help?

You probably aren't looking for a PHP client for websockets but a pushserver. http://socketo.me/docs/push

On the site of socketo.me everything is explained on how to set this up. To give you a short summary:

A pushserver is the layer between your application logic and the websocket itself. This would provide you to send requests to the pushserver which are then sent to the clients of the websocket for which the message was meant.

If you need any further explaination please let me know.

This comes late but can be helpful for someone looking to clarify this concepts.

socket_create() and socket_connect() are PHP core functions written to work with TCP and UDP protocols, but not for webSocket connections (ws://uri:port).

For the project of this question, the best is to use a ready-made websocket client package as @mitchken mentioned (ratchet/pawl, amphp/websocket-client, etc).

I have personally used amphp and it works really well, especially if you need to update the UI of an specific user/group in response to an event/notification that occurred in your backend, by sending the message with the PHP websocket client and redirecting the message to the target users in the onMessage() event of the websocket server adapter class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM