WebSocket是基于Socket的吗?为什么我只收到头信息?
本帖最后由 jdgdf566 于 2013-10-01 15:25:01 编辑 在chrome(新版支持WebSocket)里面打开的HTML页面:
<html>
<body>
<script type="text/javascript">
// 创建一个Socket实例
var socket = new WebSocket('ws://localhost:12345');
// 打开Socket
socket.onopen = function(event) {
// 发送一个初始化消息
socket.send('I am the client and I\'m listening!');
// 监听消息
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// 监听Socket的关闭
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
// 关闭Socket....
//socket.close()
};
</script>
</body>
</html>
<?php
/*
* 不使用apache,cli模式
*/
/**
* 接收端
* 单用户,即单连接
* 单线程
*/
class SocketServer {
protected $ip;
protected $port;
protected $socket;
protected $users;
protected $userIndex = 0;
protected $message;
public function __construct($ip = "127.0.0.1", $port = 12345) {
$this->ip = $ip;
$this->port = $port;
//
self::init();
//
$this->createServer();
$this->log('listenning user...');
$this->listenningUser();
}
protected function createServer() {
$errno;
$errstr;
$this->socket = stream_socket_server("tcp://" . $this->ip . ':' . $this->port, $errno, $errstr);
if (!$this->socket) {
self::log("$errstr ($errno)");
exit();
}
$this->log('server ok .');
}
protected function listenningUser() {
while (true) {
$this->userIndex++;
$user = $this->users[$this->userIndex] = stream_socket_accept($this->socket, 9999999999);
//
if (is_resource($this->users[$this->userIndex - 1])) {
$u = $this->users[$this->userIndex - 1];
$u->close();
$u = NULL;
unset($this->users[$this->userIndex - 1]);
}
//
$this->log('连入新用户');
$this->listenningMessage();
}
}
protected function listenningMessage() {
while (is_resource($this->users[$this->userIndex])) {
$this->message = stream_socket_recvfrom($this->users[$this->userIndex], 10270000);
if (!$this->message) {
$this->closeUser();
break;
}
$this->messageOperate();
}
}
function messageOperate() {
$this->log("收到消息:");
$this->log($this->message);
//mb_strstr($haystack, $needle, $before_needle, $encoding)
$this->sendMessage('done');
}
function sendMessage($msg) {
if($msg===''){
return -1;
}
return stream_socket_sendto($this->users[$this->userIndex], $msg);
}
public function closeUser() {
if (!is_resource($this->users[$this->userIndex]))
return FALSE;
@stream_socket_shutdown($this->users[$this->userIndex], STREAM_SHUT_RDWR);
@fclose($this->users[$this->userIndex]);
$this->log("用户连接断开.");
return TRUE;
}
public function shutdown() {
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
fclose($this->socket);
}
protected static function init() {
error_reporting(E_ALL ^ E_NOTICE);
set_time_limit(0);
ob_implicit_flush();
date_default_timezone_set('Asia/Shanghai');
ignore_user_abort(TRUE);
mb_internal_encoding('gbk');
}
protected static function log($message) {
echo "\r\n" . $message . "\r\n";
}
}
$server = new SocketServer();