我创建了Ratchet Web Socket服务器并试图使用SESSIONS。使用memcache进行棘轮会话数据同步
在对HTTP的Web服务器(端口80)我的PHP文件,我设置会话数据这样
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;
$memcache = new Memcache;
$memcache->connect('localhost', 11211);
$storage = new NativeSessionStorage(array(), new MemcacheSessionHandler($memcache));
$session = new Session($storage);
$session->start();
$session->set('uname', $uname);
,并连接到棘轮的WebSocket服务器的JavaScript
var RatchetClient = {
url: "ws://192.168.1.80:7070",
ws: null,
init: function() {
var root = this;
this.ws = new WebSocket(RatchetClient.url);
this.ws.onopen = function(e) {
console.log("Connection established!");
root.onOpen();
};
this.ws.onmessage = function(evt) {
console.log("Message Received : " + evt.data);
var obj = JSON.parse(evt.data);
root.onMessage(obj);
};
this.ws.onclose = function(CloseEvent) {
};
this.ws.onerror = function() {
};
},
onMessage : function(obj) {
},
onOpen : function() {
}
};
服务器脚本就像这里描述的那样工作: http://socketo.me/docs/sessions
如果客户端发送消息我获取会话数据
$memcache = new Memcache;
$memcache->connect('localhost', 11211);
$session = new SessionProvider(
new MyServer()
, new Handler\MemcacheSessionHandler($memcache)
);
$server = IoServer::factory(
new HttpServer(
new WsServer($session)
)
, 7070
);
$server->run();
class MyServer implements MessageComponentInterface {
public function onMessage(ConnectionInterface $conn, $msg) {
$name = $conn->Session->get("uname");
}
}
它的工作原理。如果我在连接到websocket之前设置了会话数据,那么uname在我的套接字服务器脚本中是非常适合的。
每当我通过ajax或从另一个浏览器窗口更改会话数据时,我的正在运行的客户端的会话数据将不会被同步。
这意味着如果我改变uname或销毁会话,套接字服务器不能识别这个。似乎是Ratchet在连接时读取会话数据一次,然后会话对象是独立的。
你能证实这种行为吗?或者我做错了什么。我认为使用memcache的目标是能够访问来自不同连接客户端的相同会话数据。
如果我在更改会话数据后重新连接到websocket,那么数据已更新。