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.
Related
I have a socket server that handles connections. Here I have a doHandshake method.
function doHandshake($received_header, $client_socket_resource, $host_name, $port) {
var_dump($received_header);
// do stuf here with header
}
When I want to connect from javascript client, It works fine, and prints all headers such as Sec-WebSocket-Key. This is how I use doHandShake method in socket server:
$header = socket_read($newSocket, 1024);
$chatHandler->doHandshake($header, $newSocket, HOST_NAME, PORT);
In the other hand I have a php client. When I connect from php client, header is a string that I send to server not a real header. Here is my client socket in php:
$host = "127.0.0.1";
$port = 8090;
$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);
Any idea how to send socket headers in php client??
Note: This is done automatically in javascript client.
The JavaScript client (a browser?) is making an HTTP request with an Upgrade header to negotiate a WebSocket connection. It's not just connecting and sending Hello Server. If you want your PHP client to do something similar, you need to implement the required protocol. The Upgrade request and the WebSocket protocol are both non-trivial to implement, so it's hard to give a quick answer, but you can partially emulate what the browser is doing like this:
$message = "GET /ws HTTP/1.1\r\n" .
"Upgrade: websocket\r\n" .
"Origin: example.com\r\n" .
"Sec-WebSocket-Key: blahblah\r\n" .
"\r\n";
You would be much better off looking for a third-party WebSocket client implemented in PHP rather than trying to write your own.
I've a webhost and I want to create a socket connection with my application .
I've this code :
<?php
$host = "127.0.0.1";
$port = 25003;
// don't timeout!
set_time_limit(0);
if (!extension_loaded('sockets')) {
die('The sockets extension is not loaded.');
}
// 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);
?>
when I run the page , it returns "Could not create socket"
I'm running the code on a share web service
what is the problem ? How can I fix it ?
I tried your code on my machine with XAMPP installed and is working, it actually does open that port, I tested with telnet through putty. Answering to your questions I think like #Jon Stirling said your hosting does not allow you to create a socket. That's why hosting companies sell web hostings packages and virtual private servers, if you want to bind a port you should look for a VPS.
I am sure you have solved this and moved jobs since you posted it but as someone who has just gone through this I would like to direct everyone who lands here to this page:
https://www.php.net/manual/en/function.socket-select.php
I was looking for a way to have a socket server that does not chew up CPU cycles and only does something when there is something to do. That solution blocks while it is waiting for connections to do something then it processes them.
Pay special attention to the comments about setting $tv_sec to null as this is the "Make Work" flag that prevents chewing up the CPU.
This allows one to create a socket server in PHP that does not chew up CPU and also processes multiple connections.
The only missing piece of the puzzle is disconnecting clients that do not disconnect themselves.
Unless there is a connection timeout that can be set I think the solution is to set $tv_sec to some suitable value, like 2 seconds, and then track the time a connection has been connected then disconnect it if it breaches some time. The downside to this is it will use CPU but if you unblock every 2 seconds then you can use that to process timeouts etc. Otherwise, you have to rely on clients disconnecting. That may not be an issue for you but in my particular usecase it is.
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
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/
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