user3801533
user3801533

Reputation: 321

Php server socket receiving continuous data from python client socket

I am trying to send data continously from the python client socket to the php server socket, I've been able to send data once and print it out. But if I put the server in a while loop to keep listening, the data it gets isn't printed out anymore. It still responds to the client if I send something back to it.

Python client code (this will be put in a function that gets called every time I send something):

import socket
import sys

def main():
    host = 'localhost'
    port = 5003  # The same port as used by the server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print >> sys.stderr, 'connecting to %s port %s' % (host, port)
    s.connect((host, port))
    s.sendall("Hello! Heartbeat 40!")
    data = s.recv(1024)
    s.close()
    print('Received', repr(data))
if __name__ == "__main__":
    main()

Php server code:

<!DOCTYPE html>
<html>
<body>

<?php

// set some variables
$host = "127.0.0.1";
$port = 5003;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");


while(true){
    // accept incoming connections
    // spawn another socket to handle communication
    $spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
    // read client input
    $input = socket_read($spawn, 1024) or die("Could not read input\n");
    // clean up input string
    $input = trim($input);
    echo "Client Message : ".$input;
   // socket_close($spawn);
}
socket_close($socket);



?>

</body>
</html>

Upvotes: 0

Views: 1397

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

PHP output is not being send to the browser immediately. Httpd server waits for php script to finish, then send the whole output to the client.

while(true){ in your php script runs indefinitely until dies on socket_accept, socket_read, or by timeout.

You need to define an exit point in your loop to eventually stop the script and send data to the browser.

Upvotes: 1

Related Questions