问题
I use php as server on localhost. I use python as client.
I want that: Client will send message to server. Server will send the same message to clients. And all of clients will show the message which is sent. But when I open 2 clients, the clients can't get answer from server when they send message.
How can I write a server with php which works correctly ? Any idea ?
server.php:
<?php
error_reporting(E_ALL);
set_time_limit(0);
header("Content-Type: text/plain; charset=UTF-8");
define("HOST", "127.0.0.1");
define("PORT", 28028);
a:
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, HOST, PORT) or die("Could not bind to socket\n");
$result = socket_listen($socket, 50) or die("Could not set up socket listener\n");
$error = 0;
while (true){
$error = 0;
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
$input = socket_read($spawn, 1024);
if (!$input) {
$error = 1;
}
if (socket_write($spawn, $input, strlen($input)) === false){
$error = 1;
}
if ($error){
goto a;
}
}
socket_close($spawn);
socket_close($socket);
client.py:
from socket import *
from threading import Thread
import sys
HOST = 'localhost'
PORT = 28028
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
def recv():
while True:
data = tcpCliSock.recv(BUFSIZE)
if not data: sys.exit(0)
print data
Thread(target=recv).start()
while True:
data = raw_input('> ')
if not data: break
tcpCliSock.send(data)
tcpCliSock.close()
回答1:
The server has to wait simultaneously for connections and data from clients; this is easy with socket_select()
. Replace your while (true){…}
loop with
$s = array($socket); // initially wait for connections
while ($r = $s and socket_select($r, $n=NULL, $n=NULL, NULL))
foreach ($r as $stream)
if ($stream == $socket) // new client
$s[] = socket_accept($socket); // add it to $s (index 1 on)
else // data from a client
if ($input = socket_read($stream, 1024))
foreach (array_slice($s, 1) as $client) // clients from index 1 on
socket_write($client, $input, strlen($input));
else
{
close($stream);
array_splice($s, array_search($stream, $s), 1); // remove client
}
Here the server socket and the client sockets are stored in the array $s
.
来源:https://stackoverflow.com/questions/38543264/how-to-write-server-for-chat-program-in-php-by-using-socket