Sending message to Ratchet WebSocket Server from another script - php

I'm not 100% sure this is worded right, but I have a Ratchet WebSocket server working correctly as a chat service. However, I want to, when a user posts a new thread on the forums, have the server automatically post a message into the chat to notify them all of this new post.
I want to do this via a quick TCP connection upon the creation of this thread. I'm still somewhat new to sockets and this area of server coding. Is there an easy way that PHP can ignore HTTP overhead in connecting to this same-server socket and simply sending a message?
Here's the code I've tried to use as a test, but ratchet does not even say it received a connection or message (ADDR and port are correct, socket_connect returns TRUE):
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$string = "Hello, a new post has been BLAH";
$Socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$Status = socket_connect($Socket, "***", "***");
$Bytes = socket_write($Socket, $string, strlen($string));
socket_strerror(socket_last_error());
socket_close($Socket);

The solution suggested on the Ratchet site is to use ZeroMQ to have your synchronous php (web server that is doing the database work for the new post) push the message to the Ratchet server.
They have some pretty good docs at http://socketo.me/docs/push

Related

PHP - Allow client to send a message to a TLS server

I'm trying to understand how we can use Php socket to let our client send messages to our Node.js server using TLS...
My problem is that i don't know how that is done in Php. Can someone please show me how that can be done in php and explain the steps please???
I have tried to search on many website to gain understanding about it. To connect to TCP server in Php we can do such:
// IPv4
$sock = #socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// IPv6
$sock = #socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
$sock->connect($address);
// now we can send to the server using socket_write
How can the same be done with TLS instead of TCP in PHP???
I'm not looking for help with the Node.js server, just php..

SignalR and PHP client using PHP's standard socket functions

Does someone know a good example or tutorial or PHP socketclient (using PHP's socket functions) to wait for updates from SignalR server? I would like to connect to socket.bittrex.com to receive updates.
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_connect($socket, gethostbyname('socket.bittrex.com'), 80) or die("Could not connect toserver\n");
echo socket_strerror(socket_last_error($socket));
This echos Success but after that i am completely stuck what to do. I want my client to subscribe to some of the signalr subscriptions and wait for updates to be sent to the client and notice updates and do something with it.
Regards,
Marcel

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.

what is socket in php? And at what condition i should go for socket connection?

I have already gone through some tutorials for socket but i couldn't get what it does. I want to know what sockets do and why is it used. This is the code I have referred.
client.php
<?php
$host = "localhost";
$port = 1024;
$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);
?>
server.php
<?php
// set some variables
$host = "localhost";
$port = 1024;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input;
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
?>
So I couldn't get the idea of where to enter the server code and client code. Usually we write server code on what it should do while getting user input.So i am extremely confused about this. Can anyone help me? Thanks in advance
In order to understand sockets I think it's important to understand networking principles. Especially the Internet Protocol and Transmission Control Protocol.
The Transmission Control Protocol is a way of breaking up a message into smaller chunks, and addressing them in such a way that the chunks can be reliably re-assembled at the receiving end. The Internet Protocol is a way of routing these chunks through the Internet.
A Socket is just a programming object that manages the details of these protocols for you. You configure the socket to connect to a given port on a given IP address. The socket manages the rest: chunking, packaging, and labeling the data. The socket encapsulates all the protocol details so that you can abstract them away and act as if you are creating a "connection" from one computer to another. As a developer, you use sockets when you need to exchange information with another computer over the Internet.
For me, the idea of a socket and what it might be used for didn't make sense until I studied computer networking. (Especially the protocols themselves, not necessarily the practical, technician side of things.) You can start with the Wikipedia articles on TCP and IP. And you can try to read individual, piecemeal articles on the web. But frankly, networking is such a huge topic that I don't think anything short of a cohesive, semester-long course or a quality textbook would be enough to truly answer this question (and to correct the gaps, oversimplifications, and exceptions that I used to keep this answer simple.)
You need to understand the concept of socket programming. To get a better idea.
Sockets are used for interprocess communication. Interprocess
communication is generally based on client-server model. In this case,
client-server are the applications that interact with each other.
Interaction between client and server requires a connection. Socket
programming is responsible for establishing that connection between
applications to interact.
Client application sends message($message) to server($host) and the
server application receives it from the client through a port($port).
The client.php runs and sends the message from a client machine. The server.php runs on the server machine which receives the message.
Try these links for examples and how to run the server and client files.
http://www.binarytides.com/php-socket-programming-tutorial/
http://www.devshed.com/c/a/php/socket-programming-with-php/

socket_accept seems to hang on the first connection

I'm trying to make a simple listener on port 8195. When I try the following code block in PHP CLI conditions, it only shows 'Test' once, then hangs. If I delete the file 'votifier.run', the file designed to be the on/off switch, it still continues to hang. It never shows 'Client connected'.
Furthermore, if I try to connect to the host via Telnet on port 8195 while the script is running, I simply get a connection failed message. It's like it's looking for one connection and just not giving up.
// Set the IP and port to listen to
$address = 'localhost';
$port = 8195;
// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
// Bind the socket to an address/port
socket_bind($sock, $address, $port);
// Start listening for connections
socket_listen($sock);
// Loop continuously
while ( file_exists('votifier.run') ) {
echo 'Test';
$client = socket_accept($sock);
if( $client ) {
echo 'Client connected';
// Don't hang on slow connections
socket_set_timeout($client, 5);
// Send them our version
socket_write("VOTIFIER MCWEBLINK\n");
// Read the 256 byte block
$block = socket_read($client, 256);
...
The answer:
socket_accept() will usually hang until a connection is made. If a connection attempt was made, the script would continue, but because the socket was being created on localhost, it would only accept connections to it from localhost.
The fix is to use your external IP rather than 'localhost' or '127.0.0.1'. Then you can Telnet to it.
I'm just guessing here, but could it be that the address you are trying to bind to should not be a hostname?
If the socket is of the AF_INET family, the address is an IP in dotted-quad notation (e.g. 127.0.0.1).
EDIT
Ok, I've taken your script and tried to reproduce your error but couldn't. There are a couple of flaws in it but none that would cause a telnet client's connection attempt to fail.
Since none of the aforementioned applies, let's go thru the checklist one by one:
sockets module loaded/compiled
localhost does resolve to 127.0.0.1
the port isn't taken by any other application running
there's no rule of any sort of firewall that would prevent communication between the telnet client and your server
the machine which you connect from is allowed to connect to the server host (try the same host if it isn't)
the file that's being checked in the while-loop does exist
you are sure that there isn't another fatal error within your script that would prevent the snippet you posted from running
These are all the possible error sources I can think of, atm. Try fixing up the minor flaws first, then go thru the checklist.
if( $client ) {
echo 'Client connected';
// Don't hang on slow connections
socket_set_option(
$client,
SOL_SOCKET,
SO_RCVTIMEO | SO_SNDTIMEO,
array('sec' => 5, 'usec' => 0)
);
// Send them our version
socket_write($client, "VOTIFIER MCWEBLINK\n");
^^^^^^^
// Read the 256 byte block
$block = socket_read($client, 256);
You should be using threads. If the client never sends anything your code will block in the read() method. Each accepted socket should be completely handled in a new thread.
You may want to check this:
PHP Votifier example for Minecraft Topsites
It explains how the code works, it's the basic function that makes the encryption, fills up the 256 blank spaces and sends the packet too. You can work a little with it as you may want to improve it.
You can see a live demo of the running php for the plugin here: http://topg.org/test_votifier

Categories