【问题标题】:Php server socket receiving continuous data from python client socketphp服务器套接字从python客户端套接字接收连续数据
【发布时间】:2017-04-30 19:01:43
【问题描述】:

我正在尝试将数据从 python 客户端套接字连续发送到 php 服务器套接字,我已经能够发送一次数据并将其打印出来。但是如果我把服务器放在一个while循环中继续监听,它得到的数据就不会再打印出来了。如果我将某些东西发回给它,它仍然会响应客户端。

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

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


    【解决方案1】:

    PHP 输出不会立即发送到浏览器。 Httpd 服务器等待 php 脚本完成,然后将整个输出发送到客户端。

    您的 php 脚本中的while(true){ 无限期运行,直到在socket_acceptsocket_read 或超时终止。

    您需要在循环中定义一个退出点,以最终停止脚本并将数据发送到浏览器。

    【讨论】:

    • 吹哦,我现在明白了。但我试图在每次发送时向我想在屏幕上更新的服务器发送心跳。这可以用套接字来完成吗?
    • 当然,但这在 PHP 中并非易事,因为您有一个中间网络服务器。我会推荐一些像 socket.io 这样的 javascriptish。唯一的事情是你需要了解它的局限性。另一种选择是使用定期拉取。在任何情况下,您都需要客户端的 ajax js 来不断更新页面而无需重新加载。
    猜你喜欢
    • 2014-11-05
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 2013-08-06
    • 2016-12-09
    • 1970-01-01
    相关资源
    最近更新 更多