I am trying to learn socket programming using PHP script for client and Python script for server. The pyhon server generates random numbers and passes it to PHP client webpage and displays it.I have managed to make it work. The problem is, when I refresh the php client webpage to get next set of random numbers, the browser hangs.
My question is, what can I do in PHP client or Python sever so that I get continously refesh my web browser and get a new set of random numbers?
Thank you all so much :-)
I have tried using global variables, $_SESSION[''], $_GET[''], $_POST[''] and AJAX but have not manage to make it work continusouly.
PHP Client
<?php
$host = "127.0.0.1";
$port = 25003;
$message = "getNum";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
// Send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// Get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "<br>Reply From Server :".$result;
// Close socket
socket_close($socket);
?>
Python server
import socket
import random
def getRandNum():
randomList=[]
lottoNums = ""
counter = 0
while counter < 6:
r = random.randint(1, 40)
if r not in randomList:
randomList.append(r)
counter = counter + 1
lottoNums = str(randomList[0]) + "-" + str(randomList[1])+ "-" + str(randomList[2])+ "-" + str(randomList[3])+ "-" + str(randomList[4])+ "-" + str(randomList[5])
return lottoNums
def server_program():
# get the hostname
host = "127.0.0.1"
port = 25003 # initiate port no above 1024
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen()
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if (data == "getNum"):
printLotto = getRandNum()
print(printLotto)
conn.send(printLotto.encode()) # send data to the client
if (data == "exit"):
conn.close() # close the connection
break
if __name__ == '__main__':
server_program()