Python套接字服务器到PHP客户端套接字

时间:2014-09-11 12:52:04

标签: php python sockets

我试图在Python和PHP之间设置套接字连接。 Python将作为服务器和PHP作为客户端。我想启动网页并检查Python中的线程是否正在运行,因此我将一个变量发送到PHP的套接字。这有效。加载页面后,用户可以单击按钮以启用或禁用该线程。所以这些按钮发回变量启用/禁用。但我无法将此数据发送回套接字。我该怎么做才能让按钮将数据压回插座?

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客户端:     

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 个答案:

答案 0 :(得分:2)

好的,我找到了解决方案。我需要定义一个循环来获取s.accept(),以便当客户端想要连接到服务器时,它会获得新的adrr值。

答案 1 :(得分:0)

要解决此问题,您需要将s.accept()放在循环中。这将确保连接保持建立。