如何为每个www客户端运行套接字服务器?
我有简单的socket_server:
<?php
// set ip and port
include('socket.php');
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "-1";
exit;
}
// bind socket to port
$result = socket_bind($socket, $host, $port) or die(socket_strerror(socket_last_error($socket)));
// start listening for connections
$result = socket_listen($socket, 3);
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "Server: Ready.";
while(1) {
// 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."<br />";
// reverse client input and send back
//$output = strrev($input) ."<br />";
$output = "output message";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
}
// close sockets
socket_close($spawn);
socket_close($socket);
?>
现在,当我尝试以这种方式运行服务器时:
<?php
//include the server.php script to start the server
include_once('server.php');
include('socket.php');
$message = "Hello Server";
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 "Reply From Server :".$result;
// close socket
socket_close($socket);
?>
我收到消息:
通常只允许使用每个套接字地址(协议/网络地址/端口)。
我在这个端口上没有任何其他通信。我检查了netstat。