1

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>
<a href="logout.php">Logout</a>
</body>
</html>

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

To solve this problem you will need to put s.accept() in a loop. This will make sure the connection remains established.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.