how to make a connection between php and android - php

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.

Related

How to test PHP socket TCP/IP Server using Terminal/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.

Convert string Hexadecimal to Binary PACK in C for SOCKET

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";

Python socket server to PHP client socket

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.

Using PHP broadcast to detect Server IP address

I want to do something like this article:
broadcast to detect Server IP address
and transfer to PHP, does it possible?
The reason is I want to send broadcast socket to server, and the server will return message then I can determine the message is what I want or not to detect the true IP of the message sender.
The code is like:
<?php
error_reporting(E_ALL);
$address = "255.255.255.255";
$port = 10000;
/* Create a udp socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "<br/>";
} else {
echo "socket successfully created.<br/>";
}
echo "Attempting to connect to '$address' on port '$port'..."."<br/>";
$result = socket_connect($socket, $address, $port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "<br/>";
} else {
echo "successfully connected to $address."."<br/>";
}
$i="theMessage";
echo "Sending $i to server."."<br/>";
socket_write($socket, $i, strlen($i));
$input = socket_read($socket, 512);
echo "Response from server is: $input"."<br/>";
$ip="";
if($input=="I want")
$ip=socket_send_from_the_IP; // just psuedocode
echo "Closing socket...";
socket_close($socket);
?>
Or is the direction of my question wrong?
I also think that I should use httprequest?
Any answer appreciated.

PHP socket_read does not return empty string ''

Hi there's problem with the socket_read function below, it does not return empty string '' after it has finished reading the data. On second call to socket_read() it just hang there, the page keep loading in browser with no return.
It works if the server close the connection, is it a must for server to close the client socket ? Thanks
$json = $_GET['json'];
/* Get the port for the WWW service. */
// $service_port = getservbyname('www', 'tcp');
$service_port = "1111";
/* Get the IP address for the target host. */
$address = "192.168.3.5";
/* 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";
die();
} 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";
die();
} else {
//echo "OK.\n";
}
$out = '';
//echo "Sending HTTP HEAD request...";
$result = socket_write($socket, $json, strlen($json));
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
die();
} else {
//echo "OK.\n";
}
echo socket_read($socket, 2048);
echo socket_read($socket, 2048);
//
// while (socket_read($socket, 2048) !== '') {
// echo $out;
//
// }
//
socket_close($socket);
Yes, that's exactly what I'd expect it to do - socket_read() will never return an empty string unless you open it a binary and the server responds with '\0'.
You seem to be trying to write an HTTP client. If you are, STOP NOW, throw away your code and go read up on the Curl extension. HTTP is not a simple protocol, and you've still got a lot to learn about how the simple stuff works. You are curently relying on the socket state and the format of the data to determine the data flow - but HTTP uses neither.
If you want to learn how HTTP works, then there's lots of documentation on the internet - the RFC's are a must, but are not a gentle introduction. If your objective is to develop an application, then use curl (or even the HTTP stream wrappers).

Categories