I am learning socket programming and experimenting using php.
I wanted to connect to a socket-server using a client and read the response of the server from the client.
Codes for :
Server.php:
$address="127.0.0.1";
$port=3343;
echo "I am here";
set_time_limit (0);
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
socket_write($client, "Welcome!!", 1024);
socket_close($socket);
Client.php
$host="127.0.0.1" ;
$port=3343;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
echo socket_read($sk, 256);
//echo "Connected";
}
On connecting,
Server output :
I am here
Client Output :
Warning: socket_read(): supplied resource is not a valid Socket resource in C:\xampp\htdocs\users\srv\test\client.php on line 16
Found the problem here.
socket_read() doesn't work with sockets which have not been created with socket_create().
Working code :
$host="127.0.0.1" ;
$port=3343;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
while (!feof($sk)) echo fgets($sk, 256); //This does the trick
//echo "Connected";
}
You are mixing the resource types.
fsockopen returns a file pointer. You need to use fread, fwrite etc. on it, and not socket_read.
socket_read accepts socket resources create with socket_create or socket_accept
Example for fsockopen from the PHP manual page:
<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br />\n";
} else {
fwrite($fp, "\n");
echo fread($fp, 26);
fclose($fp);
}
?>
fsockopen reference
socket_read reference
Related
I have a service on a server that listen to a UDP port. how can I check my service still listen on this port or not by php?
I think UDP is one-way and don't return anything on create a connection (in fact there is no connection :)) and I should write to a socket.
but, whether I write successfully to a socket or not, I receive 'true'!
my code:
if(!$fp = fsockopen('udp://192.168.13.26', 9996, $errno, $errstr, 1)) {
echo 'false';
} else {
if(fwrite($fp, 'test')){
echo 'true';
}else{
echo 'false';
}
}
do you have any suggestion for this?
You should really switch to the Sockets library for creating sockets:
$ip = '192.168.13.26';
// create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
// bind the source address
if( !socket_bind($sock, $ip, 9996) ) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
The only way to see if a socket is still open is to post a message to it, but given the nature of UDP there are no guarantees.
As PHP official documentation said
fsockopen() returns a file pointer which may be used together with the
other file functions (such as fgets(), fgetss(), fwrite(), fclose(),
and feof()). If the call fails, it will return FALSE
So you can do this to check the error
$fp = fsockopen("udp://192.168.13.26", 9996, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br />\n";
} else {
fwrite($fp, "\n");
echo fread($fp, 26);
fclose($fp);
}
I checked
php sockets read json array from java server
Sending configuration data to websocket
and spent all day on finding the solution for the following problem.
I have Client.php
<?php
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
//Connect socket to remote server
if(!socket_connect($sock , '127.0.0.1', 23))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
$data = file_get_contents ("C:\Users\(myUsername here)\Desktop\sockets\Test.txt");
$json = json_decode($data, true);
echo $data . " this is data from file\n";
echo $json . " this is decoded version\n";
echo json_encode($data) . " this is encoded version\n";
$jsonSer = serialize($json);
//socket_write($sock, count($json). "\n\r");
socket_write($sock, $jsonSer);
echo $jsonSer . " this is serialized version\n";
echo unserialize($jsonSer) . " this is unserialized message\n";
//Send the message to the server
//$sock , $message , strlen($message) , 0
//JSON.stringify(data)
if( ! socket_send($sock, $jsonSer, 1024, 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n\r");
}
echo "Message send successfully \n";
?>
And Server.php
<?php
// we create the socket (domain, type, protocol)
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
// AF_UNIX
// if false we pass error code to strerror to get a textual explanation of the error
// and exit execution of the code
if (!$socket) {
echo "Couldn't create socket";
exit(socket_strerror(socket_last_error()));
}
echo "Socket created.\n";
//$address = '127.0.0.1';
//$port = '23';
// we bind the name given in address to the socket
$socket_bound = socket_bind ($socket , '127.0.0.1', 23);
if (!$socket_bound) {
echo "Couldn't bind socket";
exit(socket_strerror(socket_last_error()));
}
echo "Socket bound.\n";
// we tell the socket to listen for incoming connections on socket and keep them in
// backlog (e.g. 25)
$backlog = 25;
$socket_is_listening = socket_listen($socket, $backlog);
if (!$socket_is_listening) {
echo "Socket is not listening";
exit(socket_strerror(socket_last_error()));
}
echo "Socket is listening...\n";
// we set socket to be non-blocking in order to fork connections
socket_set_nonblock($socket);
echo "Waiting for connections...\n";
$server_is_listening = true;
while($server_is_listening) {
// Accept incoming connection
$connection = socket_accept($socket);
if (!$connection){
// we check every 100ms for new connections
usleep(100);
}elseif($connection>0){
// fork connections
// update connections progress and tell the user
// parse json to php object or array (2nd para = 1)
//$database_data_php = json_decode($database_data_json,0);
// accept incoming connection
/* //display information about the client who is connected
if(socket_getpeername($client , $address , $port))
{
echo "Client $address : $port is now connected to us.";
}*/
$response = "Amazing, server responded";
echo "Yay !!! We have a connection\n";
if(socket_getpeername($connection , $address , $port))
{
echo "Client $address : $port is now connected to us. \n";
echo "Connection is: $connection\n";
}
//Now receive reply from server
/*socket_recv ( $connection , $data , 2045 , MSG_WAITALL )*/
//socket_read($connection, 512, PHP_NORMAL_READ);
$input = socket_read($socket, $spawn, 1024);
echo $input . " INPUT";
$buffer = socket_recv($socket, $dataIn, 1024, 0);
echo $buffer . " buffer";
if(!socket_recv($socket, $dataIn, 1024, MSG_WAITALL)){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
//print the received message
$response = unserialize($dataIn);
echo $dataIn;
//echo $buff;
socket_write($connection, $response);
//socket_close($connection);
}else{
echo "Error: ".socket_sterror($connection);
die;
}
}
I use windows 7 atm but the app will be run on unix system in command line. I open 2 cmd windows and start Server.php in first. I start Client.php in the second cmd window. I get the following errors (Server.php).
Socket created.
Socket bound.
Socket is listening...
Waiting for connections...
Yay !!! We have a connection
Client 127.0.0.1 : 50162 is now connected to us.
Connection is: Resource id #5
C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 70
PHP Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 72
Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 72
PHP Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 75
Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 75
Could not receive data: [0] The operation completed successfully.
When I sent a string there was no problem. How do I have proceed with json data please ?
Was given the solution. I need to send json as string and it worked.
Client.php below
$jsonString = "";
$handle = fopen("C:\Users\(myUsername)\Desktop\sockets\Test.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer."\n";
//echo gettype($buffer)." buffer inside";
$jsonString.=$buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
}
socket_write($sock, $jsonString);
fclose($handle);
Server.php below
$jsonString = "";
if(!socket_last_error($socket)){
while($buffer=socket_read($connection,2048)){
//echo $buffer;
$jsonString.=$buffer;
}
}
echo $jsonString;
I hope it can help someone and save some headache.
The title explains it all...
How can i connect to an IP using tcp protocol and read/get the response?
I have searched a lot but i didnt find any solution.
$socket = stream_socket_server("tcp://127.0.0.1:22", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
echo fread($conn, 26);
fclose($conn);
}
fclose($socket);
}
is this code ok?
Does the job?
Because it seems it doesn't do the job...
Thanks in advance
As suggested by others; avoid using port 22. I recommend using an obscure (unused) socket port number > 1024 such as 4444. Anything below 1024 normally requires root access.
If you need to test connectivity for 22 have your server script run additional functions.
As for sending a response back to the connected client use stream_socket_recvfrom($socket, $length, 0, $peer) instead of fread()
Then on the client side add a response listener:
client.php
$socket = stream_socket_client('tcp://127.0.0.1:4444');
if ($socket) {
$sent = stream_socket_sendto($socket, 'message');
if ($sent > 0) {
$server_response = fread($socket, 4096);
echo $server_response;
}
} else {
echo 'Unable to connect to server';
}
stream_socket_shutdown($socket, STREAM_SHUT_RDWR);
server.php
$conn = stream_socket_server('tcp://127.0.0.1:4444');
while ($socket = stream_socket_accept($conn)) {
$pkt = stream_socket_recvfrom($socket, 1500, 0, $peer);
if (false === empty($pkt)) {
stream_socket_sendto($socket, 'Received pkt ' . $pkt, 0, $peer);
}
fclose($socket);
usleep(10000); //100ms delay
}
stream_socket_shutdown($conn, \STREAM_SHUT_RDWR);
Run server.php which will listen in an endless loop listening for a non-empty packet
once server.php receives a packet it will respond back to the connected client with the received packet.
Then execute client.php which will send 'message' to server.php
Once sent it will then retrieve and echo the response from server.php which should read 'Received pkt message'
From http://php.net/stream_socket_accept
Accept a connection on a socket previously created by stream_socket_server().
That means it waits that one client wants to connect. (You just bind yourself to the port, but don't connect anything)
And fread is also the wrong function to use with socket_* functions. Correct function would be stream_socket_recvfrom().
But this really isn't what you seem to want. You appearently want to open a connection to some place. So fsockopen() is the right function:
$conn = fsockopen("127.0.0.1", 22, $errno, $errstr);
if (!$conn) {
echo "$errstr ($errno)<br />\n";
} else {
echo fread($conn, 26);
fclose($socket);
}
I am writing a simple php socket code.
Here is my code
<?php
$address="127.0.0.1";
$port=9875;
echo "I am here";
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
echo "client is here";
?>
when I run this program my browser only shows waiting for localhost.
Is there any problem in my code?
I am using xammp 1.7.4 .
Another thing I want to know if I want to get a HTTP or FTP request do I have change only the port number?
I verified the code and tested in my system and it works correctly. Showing as "client is here" after running the client.
File Name: server.php
<?php
$address="127.0.0.1";
$port=9875;
echo "I am here";
set_time_limit (0);
if(false==($socket= socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
{
echo "could not create socket";
}
socket_bind($socket, $address, $port) or die ("could not bind socket");
socket_listen($socket);
if(($client=socket_accept($socket)))
echo "client is here";
socket_close($socket);
?>
First run the server.php file.
File: client.php
<?php
$host="127.0.0.1" ;
$port=9875;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
echo "Connected";
}
?>
Now run the client.php
Your output should be like this (as I got in my system)
I am hereclient is here
If not, make sure your firewall is not blocking the request. Temporarily disable antivirus if you have one.
That is the expected behaviour of waiting.
The program you have written is a socket server which is ready to listen to the connection with the specified port, until then it will wait.
You can create a client who connects so that you will see the response "Client is here". The client can be any programming language including PHP.
Below is a sample code in PHP (I didn't verify it).
$fp = stream_socket_client("127.0.0.1:9875", $errno, $errstr);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
// Handle code here for reading/writing
}
You can check this link for sample client code in PHP.
EDIT
$host = "127.0.0.1";
$port = 9875;
$timeout = 30;
$sk = fsockopen($host, $port, $errnum, $errstr, $timeout);
if (!is_resource($sk)) {
exit("connection fail: " . $errnum . " " . $errstr);
} else {
echo "Connected";
}
Here is my code
<?php
error_reporting(E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit(0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush();
$address = 'localhost';
$port = 10000;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
do {
$out = socket_read($msgsock, 2048);
if (!empty($out)) {
if ($out == 'quit') {
break;
}
elseif ($out == 'shutdown') {
socket_write($msgsock, 'plc down', 8);
socket_close($msgsock);
break 2;
}
else {
switch ($out) {
case "KABBE": $response = "Kabbe te!"; break;
case "SZOPJ": $response = "Szopjal te!"; break;
default: $response = "Ismeretlen parancs";
}
socket_write($msgsock, $response, strlen($response));
break;
}
}
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>
and now the errors
Warning: socket_bind() [function.socket-bind]: unable to bind address [0]: Only one usage of each socket address (protocol/network address/port) is normally permitted. in C:\wamp\www\socket\socket.php on line 18
socket_bind() failed: reason: Only one usage of each socket address (protocol/network address/port) is normally permitted.
Warning: socket_listen() [function.socket-listen]: unable to listen on socket [0]: An invalid argument was supplied. in C:\wamp\www\socket\socket.php on line 22
socket_listen() failed: reason: An invalid argument was supplied.
Warning: socket_accept() [function.socket-accept]: unable to accept incoming connection [0]: An invalid argument was supplied. in C:\wamp\www\socket\socket.php on line 27
socket_accept() failed: reason: An invalid argument was supplied.
I searched on google but nothing useful.
What is the problem?
PHP also offers stream_socket_server and other stream_socket_* functions.
I found these to be more developer friendly.
Example code from php.net:
$socket = stream_socket_server("tcp://localhost:8000", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
fclose($conn);
}
fclose($socket);
}
'localhost' isn't a valid address as socket_bind doesn't accept DNS names, use the equivalent IP address '127.0.0.1'.
More info
That means you already have an open socket on your computer on that port.
Try switching to another unused port.
On Windows (which is what you seem to be working on), you can see the list of open sockets from the command line:
netstat -an
If you want to know which processes are listening to those ports, try this instead:
netstat -ban
use this code before binding:
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($socket));
exit;
}
for reference http://www.php.net/manual/en/function.socket-bind.php
You can also check http://www.php.net/manual/en/function.socket-set-option.php for details