I'm trying to setup a socket connection between Python and PHP. Python will function as server and PHP as client. I want to start the webpage and check if thread in Python is running, so I send a variable into the socket to PHP. This works. When the page is loaded the user can click on buttons to enable or disable the thread. So these buttons send back a variable enable/disable. But I'm unable to send this data back into the socket. What can I do to get the button press data back into the socket?
import time
import socket
import logging
def socketCon():
LOG_FILENAME = "logging.out"
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
logging.info("Started setting up the socket to php connection")
HOST = '127.0.0.1' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
logging.info("Connected to Server")
except socket.error, msg:
logging.info('Socket Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
s = None
continue
try:
s.bind(sa)
logging.info("Bind Complete")
s.listen(1)
logging.info("Now Listening to socket")
except socket.error, msg:
logging.info('Socket bind/listening Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
s.close()
s = None
continue
break
if s is None:
logging.info("could not open socket")
#try:
logging.info("Waiting on Socket to Accept")
conn, addr = s.accept()
logging.info("Connected by "+str(addr))
# Get data from the socket
#data1 = conn.recv(1024)
#logging.info("What did the user send from the Website: "+str(data1))
# Send data to socket
alarm = "Enabled"
conn.send(alarm)
logging.info("Send status to client socket: "+str(alarm))
run = True
logging.info("Waiting for user button press")
# Wait for user button press from website
while run == True:
# Get the button press from the website
data2 = conn.recv(1024)
logging.info("Recieving data: "+str(data2))
if data2 == 0:
logging.info("What did the user select from the Website: "+str(data2))
run = False
# close the socket
conn.close()
def runTest():
#while:
try:
socketCon()
except:
print "There was a problem"
socketCon()
#runTest()
PHP client:
if(isset($_SESSION['id']))
{
// Put stored session variables into local PHP variable
$uid = $_SESSION['id'];
$usname = $_SESSION['username'];
$result = "Login data: <br /> Username: ".$usname. "<br /> Id: ".$uid;
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();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
//$output="Client Logged on via website" ;
//socket_write($socket, $output, strlen ($output)) or die("Could not write output\n");
// Get the response from the server - our current telemetry
$resultLength = socket_read($socket, 1024) or die("Could not read server response\n");
$result4 = $resultLength;
if($result4 === "Enabled")
{
echo "Alarm is Running";
$disabled1 = "disabled='disabled'";
$disabled2 = "";
}
elseif($result4 === "Disabled")
{
echo "Alarm is not running";
$disabled1 = "";
$disabled2 = "disabled='disabled'";
}
// close the socket
socket_close($socket);
}
else
{
$result = "You are not logged in yet";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $usname ;?> - Alarm Enable/Disable</title>
</head>
<body>
<br>
<?php
echo $result;
?>
<br>
<?php
echo $result2;
?>
<br>
<form id="form" action="user.php" method="post" enctype="multipart/form-data">
<input type='submit' name='submit1' value='Enable Alarm' <?php echo $disabled1; ?> />
<input type='submit' name='submit2' value='Disable Alarm' <?php echo $disabled2; ?> />
</form>
<article>
<?php
if (isset($_POST[submit1]))
{
/*// 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();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
*/
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
$input="Enable";
socket_write($socket, $input, strlen ($input)) or die("Could not write input\n");
echo "Send Enable back into socket to the Server";
// close the socket
socket_close($socket);
// Now direct to user feed
header("Location: logout.php");
}
if (isset($_POST[submit2]))
{
/*// 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();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
*/
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
$input="Disable";
socket_write($socket, $input, strlen ($input)) or die("Could not write input\n");
echo "Send Disable back into socket to the Server";
// close the socket
socket_close($socket);
// Now direct to user feed
header("Location: logout.php");
}
?>
</article>
<br>
Logout
</body>
</html>
Ok I foudn the solution. I need to define a loop to get the s.accept() so that when the client want's to connect to the server it gets the new adrr values.
To solve this problem you will need to put s.accept() in a loop. This will make sure the connection remains established.
Related
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.
I need help with a code that I must pass from PHP to C.
The code allows to send via SOCKET an instruction to a remote device.
It works perfect for me in PHP, but I have to convert it to C. Everything is fine, except PHP's pack () function, I do not see how to replace it in C.
Basically I have to pass this:
$message = pack("H2H8H2H4H4", "a5", "00000001", "5e", "0000", "bc19");
A mesaje_in_c = ¿ ?
I would appreciate the support you can give me, thanks!
This is the PHP code:
<?php
$host = "192.168.0.140";
$port = 8081;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
print "socket_create() falló: razón: " . socket_strerror(socket_last_error()) ."\n";
} else {
print "create socket OK.\n";
}
socket_set_option(
$socket,
SOL_SOCKET, // socket level
SO_RCVTIMEO, // timeout option
array(
"sec"=>10, // Timeout in seconds
"usec"=>0 // I assume timeout in microseconds
)
);
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
if ($result === false) {
print "socket_connect() falló.\nRazón: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
print "connect to server OK.\n";
}
$message = pack("H2H8H2H4H4", "a5", "00000001", "5e", "0000", "bc19");
echo "Message To server Bin: ".$message."\n";
echo "Message dec: ";
print_r(unpack("H*", $message))."\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");
print "Reply From Server Bin:".$result."\n";
$resultHex = unpack("H*", $result);
print "Reply From Server Hex:";
print_r($resultHex)."\n";
// close socket
socket_close($socket);
?>
And this is the C code to finish:
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc , char *argv[]){
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char *message , server_reply[2000];
int recv_size;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
server.sin_addr.s_addr = inet_addr("192.168.0.140");
server.sin_family = AF_INET;
server.sin_port = htons(8081);
//Connect to remote server
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected");
//Send some data
message = "a5000000015e0000bc19";
// ???? message = pack("H2H8H2H4H4", "a5", "00000001", "5e", "0000", "bc19");
if( send(s , message , strlen(message) , 0) < 0)
{
puts("Send failed");
system("pause");
return 1;
}
puts("Data Send\n");
//Receive a reply from the server
if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
{
puts("recv failed");
}
puts("Reply received\n");
//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
puts(server_reply);
system("pause");
return 0;
}
I would appreciate the support you can give me, thanks!
Does it work?
char message[] = "\xa5\x00\x00\x00\x01\x5e\x00\x00\xbc\x19";
All this code is run on my local machine
Hi.
I am trying to learn how to properly use sockets.
I created two scripts, the following:
socket.php :
<?php
$address = "10.0.1.13";
$port = 19132;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if($socket === false){
console("Failed to create socket.");
exit(1);
}
if(socket_bind($socket, $address, $port) === false){
console("CANNOT BIND SOCKET -BYE!");
exit(1);
}
$stop = false;
$start = microtime(true);
console("Socket started ($address) : $port");
while(!$stop){
}
socket_close($socket);
console("Script stopped.");
function console($message){
echo $message . "\n";
}
?>
reader.php :
<?php
$address = "10.0.1.13";
$port = 19132;
/* 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();
if (($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if(socket_connect($socket, $address, $portph) === false){
console("CANNOT CONNECT SOCKET -BYE!");
exit(1);
}
//socket_set_nonblock($socket);
console("success!");
function console($message){
echo $message . "\n";
}
?>
The goal is too run socket.php, and have reader.php connect to the socket. Though, I am always getting Can't assign requested address when trying to connect to socket with reader.php. I don't understand what am I doing wrong.
How can I fix this?
As per PHP.net
Note:
This function must be used on the socket before socket_connect().
you can refer to - [http://php.net/manual/en/function.socket-bind.php][1]
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.
here is a method in an android application, listen to message send by a php file in a web server
public void run() {
try {
Log.i("------Connect--------", "------------1-------------");
//System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
Log.i("------xxxxxxxxx--------", "------------2-------------");
while (true) {
x++;
Log.i("------xxxxxxxxxx--------","-----------"+x+"-----------");
Log.i("------xxxxxxxxxx--------", "-----------pret de listener------------");
Socket client = serverSocket.accept();
Log.i("------xxxxxxxxxx--------", "-----------en cours de listening-------------");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
Log.i("------xxxxxxxxxx--------", str + "-------------");
//System.out.println("S: Received: '" +);
} catch(Exception e) {
Log.i("------xxxxxxxxxx--------", "S: Error");
} finally {
client.close();
Log.i("------xxxxxxxxxx--------","S: Done.");
}
}
} catch (Exception e) {
Log.i("------xxxxxxxxxx--------","S: Error");
}
the next php code to send a string to an ip from emulator android
<?php
error_reporting(E_ALL);
/* define socket server ip and port here.. */
$socket_ip = "10.0.0.2";
$socket_port = 6060;
set_time_limit(0);
/* create a tcp/ip socket.. */
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
$error = socket_strerror(socket_last_error());
echo "socket_create() failed: [$result] $error\n";
} else {
echo "socket_create() ok.\n";
}
/* connect to socket server ip and port */
$result = socket_connect($socket, $socket_ip, $socket_port);
if ($result === false) {
$error = socket_strerror(socket_last_error($socket));
echo "socket_connect() failed: [$result] $error\n";
} else {
echo "socket_connect() ok.\n";
}
$in = "\r\n\r\n";
$len = strlen($in);
echo "sending input data request.\n";
socket_write($socket, $in, $len);
echo "socket_write() ok.\n";
echo "reading return data.\n";
while ($out = socket_read($socket, 6060)) {
echo "socket_read() : $out";
}
echo "closing the socket.";
socket_close($socket);
echo "socket_close() ok.\n\n";
?>
the problem is when execute command '$ result = socket_connect ($ socket, $ socket_ip, $ socket_port);'finds no answer
If you want to pull data from the server, use Josephs tutorial. If you want to push data from the server to the phone, use Google Cloud Messaging. This way the server can let the phone know that there is new data available. You still need to pull it then. You should not push data through a socket to the phone.