使phantomjs,socket.io和gevent-socketio一起工作 [英] Getting phantomjs, socket.io and gevent-socketio to work together
问题描述
我正在尝试构建一个使用Phantomjs 1.7(模拟浏览器)的应用程序,并创建一个Python后端来触发一些事件并收集数据.
I am trying to build an application that utilizes Phantomjs 1.7 (simulating a browser) and create a Python back-end to fire up some events and collect data.
问题是Phantomjs和我的Python程序这两个进程需要双向通信.问题是在page.evaluate
内部,我不能:
The problem is that the two processes Phantomjs and my Python program need to communicate bi-bidirectionally. The problem is that inside page.evaluate
I cannot:
- 传递任何复杂的对象,例如"fs"(从stdin中读取)
- 创建一个WebSocket以连接到我的Python脚本
- 任何其他形式的进程间通信都受到限制
所以我的解决方案很简单:
So my solution is simple:
- 将socket.io js注入我正在查看的页面中.
- 连接到使用gevent-socketio实现的python服务器
当我尝试从页面内部进行连接时,评估得到:
When I try to connect from inside page.evaluate I get:
Unexpected response code: 404
这是Phantomjs脚本:
Here is the Phantomjs script:
var page = require("webpage").create();
page.onAlert = function(msg) { console.log("alert>>>" + msg); };
page.onConsoleMessage= function(msg) { console.log(msg); };
page.open("http://google.com", function() {
page.injectJs("socket.io.js");
page.evaluate(function() {
var socket = new io.Socket();
socket.connect('localhost:5051/test');
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('signal',function(data) {
console.log('Received a signal: ',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
socket.send("kakalq");
});
//phantom.exit();
});
这是服务器端Python脚本:
And here is the server-side Python script:
from socketio import socketio_manage
from socketio.server import SocketIOServer
from socketio.namespace import BaseNamespace
class MyNs(BaseNamespace):
def initialize(self):
print "connected"
self.emit('connect')
def disconnect(self, *args, **kwargs):
print "diconnecting"
super(MyNs, self).disconnect(*args, **kwargs)
def signal(self, message):
print "received signal", message
self.emit("okay", "this will be sent to js")
def start(environ, start_response):
if environ['PATH_INFO'].startswith('/test'):
return socketio_manage(environ, { '/test': MyNs })
if __name__ == "__main__":
server = SocketIOServer( ('', 5051), start,policy_server=False )
server.serve_forever()
推荐答案
我对为什么它不起作用的猜测是PhantomJS仅支持WebSockets的旧版本. PhantomJS 2.0必须等待几个月才能支持当前版本的WebSockets.
My guess for why it does not work is that PhantomJS only supports the old, deprecated version of WebSockets. We have to wait a few months for PhantomJS 2.0 for it to support the current version of WebSockets.
这篇关于使phantomjs,socket.io和gevent-socketio一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!