Getting phantomjs, socket.io and gevent-socketio to work together

I am trying to create an application that uses Phantomjs 1.7 (simulates a browser) and builds Python to fire some events and collect data.

The problem is that two Phantomjs processes and my Python program have to communicate bi-bidirectionally. The problem is that inside page.evaluate

I cannot:

  • pass any complex objects like "fs" (read from stdin)
  • create a WebSocket to connect to my Python script
  • any other form of interprocess communication is limited.

So my solution is simple:

  • Embed socket.io js into the page I am viewing.
  • Connect to my python server which is implemented with gevent-socketio

When I try to connect from within the page. evaluate, I get:

Unexpected response code: 404

      

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();
});

      

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()

      

+2


source to share


1 answer


My guess why this doesn't work is that PhantomJS only supports the old, legacy version of WebSockets. We need to wait a few months for PhantomJS 2.0 to support the current version of WebSockets.



+3


source







All Articles