I'm trying to set up a communication via socket between a PHP page (client) and a Python script (server). The PHP page has a button that, when clicked, sends "next" to the server. This part works but the problem happens when I refresh the page. In this situation I'm not writing anything to the server, yet, the function recv()
of my server seems to receive something (an empty string) because the next lines are executed. Can someone tell me what's going on ?
client.php
<?php
$host = '127.0.0.1';
$port = 5353;
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Could not create socket\n');
$result = socket_connect($socket, $host, $port) or die('Could not connect to server\n');
if(isset($_POST['btnNext'])) {
$msg_to_server = 'next';
socket_write($socket, $msg_to_server, strlen($msg_to_server)) or die('Could not send data to server\n');
$msg_from_server = socket_read($socket, 1024) or die('Could not read server response\n');
echo 'Server said : ' . $msg_from_server;
}
?>
<form action='' method='POST' >
<button name='btnNext' type='submit'>Next</button>
</form>
server.py
import socket
host = '127.0.0.1'
port = 5353
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
while True:
client_socket, addr = server_socket.accept()
# doesn't wait for the client response :
msg_from_client = client_socket.recv(5000).decode()
print('Client said : ' msg_from_client)
CodePudding user response:
change your php part to this.
<?php
$host = '127.0.0.1';
$port = 5357;
if(isset($_POST['btnNext'])) {
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Could not create socket\n');
$result = socket_connect($socket, $host, $port) or die('Could not connect to server\n');
//creating socket connection under condition o.w making those empty str
$msg_to_server = 'next';
socket_write($socket, $msg_to_server, strlen($msg_to_server)) or die('Could not send data to server\n');
$msg_from_server = socket_read($socket, 1024) or die('Could not read server response\n');
echo 'Server said : ' . $msg_from_server;
socket_close($socket); //probably ?
}
?>