简体   繁体   English

PHP服务器套接字从python客户端套接字接收连续数据

[英]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. 我试图将数据从python客户端套接字连续发送到php服务器套接字,我已经能够发送一次数据并打印出来。 But if I put the server in a while loop to keep listening, the data it gets isn't printed out anymore. 但是,如果我将服务器置于while循环中以继续监听,则不再打印输出的数据。 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): Python客户端代码(这将放置在每次我发送内容时都会调用的函数中):

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: PHP服务器代码:

<!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>

PHP output is not being send to the browser immediately. PHP输出不会立即发送到浏览器。 Httpd server waits for php script to finish, then send the whole output to the client. Httpd服务器等待php脚本完成,然后将整个输出发送到客户端。

while(true){ in your php script runs indefinitely until dies on socket_accept , socket_read , or by timeout. while(true){在您的php脚本中无限期运行,直到死于socket_acceptsocket_read或超时为止。

You need to define an exit point in your loop to eventually stop the script and send data to the browser. 您需要在循环中定义一个退出点,以最终停止脚本并将数据发送到浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM