我正在尝试在php5 +&中使用websocket win7x64环境。 首先,我使用stream_socket_server通过php-websocket示例创建服务器套接字(保存为test_socket1.php)
....
$url = 'tcp://127.0.0.1:8000';
$this->context = stream_context_create();
if(!$this->master = stream_socket_server($url, $errno, $err, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $this->context))
{
die('Error creating socket: ' . $err);
}
$this->allsockets[] = $this->master;
$this->log('Server created');
....
....
public function run()
{
while(true)
{
$changed_sockets = $this->allsockets;
@stream_select($changed_sockets, $write = null, $except = null, 0, 5000);
foreach($changed_sockets as $socket)
{
if($socket == $this->master)
{
if(($ressource = stream_socket_accept($this->master)) === false)
{
$this->log('Socket error: ' . socket_strerror(socket_last_error($ressource)));
continue;
}
else
{
....
运行命令:php test_socket1.php,得到“Server created”输出。 之后,我在chrome / IE中运行client.html,它将进入stream_select而不会返回超时。 所以我使用另一个例子PHP-Websockets,它使用socket_create,(保存为test_socket2.php)
....
$this->master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Failed: socket_create()");
socket_set_option($this->master, SOL_SOCKET, SO_REUSEADDR, 1) or die("Failed: socket_option()");
socket_bind($this->master, '127.0.0.1', '8000') or die("Failed: socket_bind()");
socket_listen($this->master,20) or die("Failed: socket_listen()");
$this->sockets['m'] = $this->master;
$this->stdout("Server started\nMaster socket: ".$this->master);
....
运行命令:php test_socket2.php,得到“Server started ...”输出。然后我运行相同的client.html,工作正常,受到尊重。为什么这个有用? client.html如下,
var host = "ws://127.0.0.1:8000"; // SET THIS TO YOUR SERVER
try {
socket = new WebSocket(host);
log('WebSocket - status '+socket.readyState);
socket.onopen = function(msg) {
log("Welcome - status "+this.readyState);
};
socket.onmessage = function(msg) {
log("Received: "+msg.data);
};
socket.onclose = function(msg) {
log("Disconnected - status "+this.readyState);
};
}
catch(ex){
log(ex);
}
我还在test_socket1中添加了一些检查点,试图找出问题但运气不好并且有几个未使用的结果,
所以我的问题是为什么这两者有不同的结果? stream_socket需要更多预配置的东西吗?感谢。