0
我想連續發送數據從python客戶端套接字到php服務器套接字,我已經能夠發送數據一次並打印出來。但是如果我把服務器放在while循環中繼續監聽,它所得到的數據不會再被打印出來。如果我發回一些東西,它仍然會迴應客戶。從python客戶端套接字接收連續數據的PHP服務器套接字
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>
吹牛哦,我現在明白了。但我試圖發送心跳到我想每次發送它時在屏幕上更新的服務器。這可以用套接字來完成嗎? – user3801533
當然,但它在PHP中並不重要,因爲您有一箇中介Web服務器。我會推薦像http://socket.io這樣的javascriptish。唯一的是你需要了解它的侷限性。另一種選擇是使用定期拉。無論如何,您需要在客戶端上使用ajax js,以便在不重新加載的情況下不斷更新頁面。 –