0

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()
2
  • PHP runs server-side and only executes for the duration of the HTTP request. So you can't have the PHP script continuously running to receive data, in that environment. A web page with a websocket connection to a websocket server would be able to do this and keep receiving info in real-time. HTTP is a stateless, request-response protocol, so not suited to streaming of data. Commented Jun 7, 2023 at 10:12
  • But if you just want to experiement with TCP sockets, you could simply use PHP from the command-line instead of via a webserver. Commented Jun 7, 2023 at 10:12

1 Answer 1

0

I believe the solution would be to not using two backend languages but one front end (HTML with JavaScript) connecting with the backend (Python). That way you can stream data from the back to the front without depending on the timeout of a socket connection in the back.

Here's a link! to an example.

Best, e.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.