How to test PHP socket TCP/IP Server using Terminal/PHP? - php

I have a server up online, and I made a simple TCP/IP Server using PHP to handle a certain port. The code I use is found below:
<?php
error_reporting(E_ALL);
/* Allow the script to wait for connections. */
set_time_limit(0);
/* Activate the implicit exit dump, so we'll see what we're getting
* while messages come. */
ob_implicit_flush();
$address = '123.456.789.123';
$port = 1234;
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";
}
//clients array
$clients = array();
do {
$read = array();
$read[] = $sock;
$read = array_merge($read,$clients);
$write = NULL;
$except = NULL;
$tv_sec = 5;
// Set up a blocking call to socket_select
if(socket_select($read, $write, $except, $tv_sec) < 1)
{
// SocketServer::debug("Problem blocking socket_select?");
echo "socket continuing";
continue;
}
// Handle new Connections
if (in_array($sock, $read)) {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
$clients[] = $msgsock;
$key = array_keys($clients, $msgsock);
$msg = "\Welcome to the PHP Test Server. \n" .
"You are the customer number: {$key[0]}\n" .
"To exit, type 'quit'. To close the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
}
// Handle Input
foreach ($clients as $key => $client) { // for each client
if (in_array($client, $read)) {
if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($client)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
unset($clients[$key]);
socket_close($client);
break;
}
if ($buf == 'shutdown') {
socket_close($client);
break 2;
}
$talkback = "Client {$key}: You said '$buf'.\n";
socket_write($client, $talkback, strlen($talkback));
echo "$buf\n";
}
}
} while (true);
socket_close($sock);
?>
The script just basically runs and allows for more than one connection to run. After uploading the code to the server, I connected to the server, got to the directory where the file is, and then ran php filename.php. It does not show any warning or errors.
However, I need to further configure this TCP/IP Server and do things based on the input it receives. Right now, when I run php filename.php, it doesn't show anything (I'm guessing because all the outputs are written to the socket, and not echoed).
How do I test this TCP/IP Server that I made? telnet is out of the question since it's not secure. Right now I'm looking for nothing too complicated, so the Terminal or another simple PHP File would be a good choice.

I would try to use react/socket for your testing purposes. It allows to create clients and servers pretty fast. Try this client code just to get started:
<?php
require_once __DIR__ . "/vendor/autoload.php";
$loop = React\EventLoop\Factory::create();
$connector = new React\Socket\Connector($loop);
$connector->connect('127.0.0.1:1234')->then(function (React\Socket\ConnectionInterface $conn) use ($loop) {
$conn->on('data', function ($data) use ($conn) {
echo $data;
$conn->close();
});
});
$loop->run();
The documentation is here.

Related

Multiple Socket Connection Using PHP

I have made a socket connection using php which is working perfectly below is the code for single socket but not working with multiple connections only accepts one connection at a time
error_reporting(E_ALL);
// sudo lsof -t -i:10000
// php -f server.php
/* 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 = '192.168.5.155';
$port = 3490;
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, 1024) === 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;
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_BINARY_READ))) {
/*echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;*/
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
break 2;
}
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
if($buf != '')
{
$req_get = $talkback;
$file = time();
$fp = fopen('data/'.$file.'.txt', 'a+');
fwrite($fp, $req_get);
fclose($fp);
socket_write($msgsock, $talkback, strlen($talkback));
}
//echo "$buf\n";
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
I need a help to just make it work with multiple connection with clients.
After that i need to make entry into database from client sent data.
You can't listen many sockets using blocking socket connections at the same time. What you need is non-blocking socket connections with socket_select method instead of socket_accept.
My suggestion is to use some kind of PHP event-loop implementations (like reactphp).
Anyway, if you still want to implement it yourself, you can check the example of stream_select usage in reactphp/event-loop StreamSelectLoop implementation.

implement chat service using socket programming in php

I wanted to implement a chat service in PHP for which I am using socket programming.
Below are the client and server file I found to implement it:
Server.php
#!/usr/local/bin/php -q
<?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 = '192.168.1.53';
$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;
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
socket_write($msgsock, $talkback, strlen($talkback));
echo "$buf\n";
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>
Client.php:
<?php
error_reporting(E_ALL);
echo "<h2>TCP/IP Connection</h2>\n";
/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');
/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK.\n";
}
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
echo $out;
}
echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
?>
But I am not able to understand one thing in this process.I will be hosting this application to a remote server and both the files will reside in that server.Now the line socket_connect() in client.php would try to connect with the IP address I pass to this function as a parameter,and,for the application to work I need both the server.php and client.php files.
Now, let us assume that the client.php sends a request to a particular user X,now for the user X to accept that request,he should also have a server.php file to accept the HTTP request made,but the server.php is on the server where the application is hosted.So how the user X's machine will be able to accept the request?
Can anyone please tell how this will be handled or please correct me if I misunderstood the process?

Socket communication between PHP server and ActionScript

I am studying about socket communication and succeeded to connect between PHP server and PHP client. Now I want to do same thing with PHP server and ActionScript client.
http://php.net/manual/en/sockets.examples.php
I read this and could communicate between server and client on 2 Windows command prompts both in PHP.
So now I changed the client to ActionScript but it seems connecting to server but the string or number is not sent.
Does socket communication matter only address and port regardless of language? Or I cannot use two different languages to communicate?
For server, I used example 1 code in the URL above, changed address and port.
AS client is here, I wrote the minimum code, this would just send number when the file is run.:
import flash.net.Socket;
import flash.events.*;
import flash.net.LocalConnection;
var s:Socket = new Socket;
s.connect("localhost",10000);
s.writeByte( 10 );
s.flush();
trace("sent");
And this is PHP server code.
#!/usr/local/bin/php -q
<?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;
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
socket_write($msgsock, $talkback, strlen($talkback));
echo "$buf\n";
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>

sending commands to tk103 gps tracker

I'm working on a realtime gps tracker web application using php.
The tracker reference is tk103, I can receive information from the tracker and store it into database.
GPRS mode of the device is enabled, my question is :
How can I send command from my server to the device using php.
Thanks in advance
it' depends on which protocol are you using to send data from tk103 device to server if you are using TCP/IP protocol once data came from device you should replay back with your command.
you show configure in device to ask or invoke to request for command.
we are configure like
1) imei:359710047059226,tracker,15/03/18 12:17,,F,121703.000,A,1255.2746,N,07736.8209,E,0.00,208.00,0.00,1,0;
id device send this command we are storing only to data base
2) imei:359710047059226,tracker,15/03/18 12:17,,F,121703.000,A,1255.2746,N,07736.8209,E,0.00,208.00,0.00,1,1;
last bit data we are testing
if 0 means only storing replay with :OK
if 1 means replay with :CMD GPRS 001 like some commands
[`#!/usr/local/bin/php -q
<?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 = '192.168.1.53';
$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;
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
socket_write($msgsock, $talkback, strlen($talkback));
echo "$buf\n";
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>
`]1

What difference with socket in windows using php?

I have wrote one app in php which uses sockets. Suddenly there was a need to run it on windows, before this it was only on linux with no problems.
Currently problem is in socket_recv function which is used like $bytes = #socket_recv($socket, $data, 2048, MSG_DONTWAIT);. First of all on the windows there isn't any MSG_DONTWAIT constant as i get nocite about it. I found a small fix for it like:
if (!defined('MSG_DONTWAIT'))
define('MSG_DONTWAIT', 0x40);
Then it says:
Warning: socket_recv(): unable to read from socket [0]: The operation completed
successfully.
After it i decided to ask may be there is some difference with work with sockets on Windows and Linux?
I believe there is a difference when you create socket in windows as opposed to linux.
Try something like this:
<?php
// Init
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$address = '127.0.0.1';
$port = 10000;
// On Windows we need to use AF_INET
$domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);
// Create socket
if (($sock = socket_create($domain, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
// Bind socket to port
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
// start listening
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;
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
socket_write($msgsock, $talkback, strlen($talkback));
echo "$buf\n";
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>

Categories