Python长轮询服务器(与现有PHP服务器相同)

时间:2017-01-01 17:28:38

标签: php python server

我有一个简单的PHP脚本(在xampp上运行)用于长轮询服务器,但我想将其转换为Python并使其成为Python服务器。我对没有经验的python(特别是涉及到Web服务器)感到非常友好,我还没有找到任何可以做同样事情的Python网络服务器的简单解决方案,所以我想知道,任何人都可以帮我翻译这个脚本从php到Python。

我的php脚本执行此操作:它从客户端获取时间戳,然后将其与文件的当前修改时间进行比较,如果它们不同,则会发送文件内容和以JSON编码的新时间戳。 这是我的代码:

<?php
$filename = dirname(__FILE__).'/data.txt';

$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);

while ($currentmodif <= $lastmodif){
    usleep(10000);
    clearstatcache();
    $currentmodif = filemtime($filename);
}

$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>

1 个答案:

答案 0 :(得分:1)

以下链接包括一个简单的python服务器示例,以及一些其他信息,它应该为python tcp / ip客户端/服务器编程提供一个很好的起点:

TCP / IP客户端和服务器 - https://pymotw.com/2/socket/tcp.html

python wiki - TCP沟通 - https://wiki.python.org/moin/TcpCommunication

Python文档 - 20.17.4.1。 SocketServer.TCPServer示例 - https://docs.python.org/2/library/socketserver.html#SocketServer.TCPServer