Php socket headers from client - php

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.

Related

How to receive data from server using PHP socket

I am having a hard time getting data from the server. Basically server waits for a connection from anyone using correct username and password. So when I use that using local explorer it shows the data on the browser.
Now what I was trying to do is, get this data using socket and forward it to another server address. But I could not even connect to the server to get the data like I get on the browser. Here is what I have tried:
$host = "192.168.1.4/online?user=dneb&pass=mella88";
$port = 1850;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) 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 "server Message : ".$input;
When I run this code I get warning message:
Warning: socket_bind(): Host lookup failed [11004]: The requested name is valid, but no data of the requested type was found. in C:\xampp\htdocs\socket\client.php on line 10
Could not bind to socket
Or suggest other methods to use.
When you create a socket server, you don't specify the host as the full URL to your script; that's why the bind is failing.
Take a look at this sample: http://www.php.net/manual/en/sockets.examples.php
please try changing
$host = "192.168.1.4";

Host a PHP Socket server program in AWS

My requirement is to host a php socket server script in AWS EC2. and communicate to that socket server. This is what I have done so far but its not working.
server.php script that acts a socket server and listens to clients:
<?php
// set some variables
$host = "127.0.0.1";
$port = 53;
// 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);
In AWS security group, I have added following Inbound rule:
I run the server,php script from SSH using command "php server.php".
I tried to connect to the server from SocketTest tool where I entered following
value
host: 52.xx.xx.xxx (masked the actual value here) and port: 53
I am not able to connect to the socket server. It would be really helpful if someone can guide me if I am missing anything here
Please note that same server.php program is working fine when tested in local xampp server
You have used '127.0.0.1' as host in server script.
You have to replace it with your server's private IP address.

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/

php sockets - listen on the "internet"?

Using the example from http://www.codeproject.com/Tips/418814/Socket-Programming-in-PHP
SERVER.PHP:
// set some variables
$host = "127.0.0.1";
$port = 25003;
// 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);
CLIENT.PHP:
$host = "127.0.0.1";
$port = 25003;
$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);
As you can see, the server is listening on 127.0.0.1:port and client is connecting to 127.0.0.1:port
However, I want my client and server to be on two different servers.
For example:
My server will listen be on IP 11.22.33.44:1234 and my client will be connecting from IP 12.23.45.66:1234
I am going to be using linux servers, but right now I am doing this on my windows machine.
So I want to listen on my external IP.
When I enter my external IP as host, I get errors thrown.
Warning: socket_bind(): unable to bind address [10049]: The requested address is not valid in its context. in C:\xampp\htdocs\server.php on line 12
Warning: socket_listen(): unable to listen on socket [10022]: An invalid argument was supplied. in C:\xampp\htdocs\server.php on line 14
Warning: socket_accept(): unable to accept incoming connection [10022]: An invalid argument was supplied. in C:\xampp\htdocs\server.php on line 17
Warning: socket_read() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\server.php on line 18
Warning: socket_write() expects paramet
er 1 to be resource, boolean given in C:\xampp\htdocs\server.php on line 20
How can I do this?
Thanks.
Since you're (speculation!) probably hosting this service behind a proxy, router, firewall, or other perimeter device, your box won't have direct access to bind to the external IP. Therefore, leave it bound to localhost and forward (open) the applicable ports from the perimeter device to your server.
If, for example, you're using AWS to host, you would set the firewall ACL to permit your socket ports to both servers and then the connections should flow through.
This is akin to binding your Apache web services to the localhost IP address of the server.
Alternatively, if you're not hosting this and communication is happening on a local network, then you should be able to at least bind to the assigned/internal IP address of each local network card.
open cmd and write that
php -f C:\xampp\htdocs\server.php
your code

Categories