Handle inter-process communication between PHANTOMJS and Golang processes via hixie-76 websockets

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Although PHANTOMJS version 1.9 does has WebSocket support, which is limited to the hixie-76 draft of the protocol. PHANTOMJS 2.0 is scheduled to include the more modern RFC 6455 version of WebSockets. When writing scripts for Phantomjs this intend to use WebSocket connections, we must ensure that the server supports the H ixie-76 version of the protocol.

Package Mainimport ("Bufio" "Code.google.com/p/go.net/websocket" "Github.com/garyburd/redigo/redis"//"github.com/ Davecgh/go-spew/spew "" Crypto/md5 "" Encoding/hex "" io "" net/http "" OS "" StrConv "" Strings "" Time ") const PS = string (OS. PathSeparator) Const PH = "/" Var (pwd, _ = os. GETWD () JSON = WebSocket. Jsonmessage = WebSocket. Messageactiveclients = Make (Map[clientconn]int64) redis_host Stringrdpool *redis. Poolupload_dir string) type clientconn struct {websocket *websocket. Connclientip string}func init () {f, err: = OS. Open ("config") if err! = Nil {panic (err)} else {defer f.close ()}buf: = Bufio. Newreader (f) line, err: = buf. ReadString (' \ n ') if err! = Nil | | Io. EOF = = Err {panic (err)} else {redis_host = strings. Trimspace (line) Rdpool = Initredis (redis_host)}line, err = buf. ReadString (' \ n ') if err! = Nil | | Io. EOF = = Err {panic (err)} else {Upload_dir = strings. Trimspace (line)}}func sockserver (ws *websocket. Conn) {var err errorvar clientmessage stringvar servermessage stringDefer func () {if Err = ws. Close (); Err! = nil {pp ("Websocket could not being closed", err. Error ())}} () client: = ws. Request (). REMOTEADDRPP ("Client connected:", client) Sockclient: = Clientconn{ws, client}activeclients[sockclient] = time. Now (). Unix () pp ("Number of clients connected:", Len (activeclients)) for {err = message.receive (WS, &clientmessage) if err! = N Il {pp ("Websocket disconnected Waiting", err. Error ()) Delete (activeclients, sockclient) pp ("Number of clients still connected:", Len (activeclients)) Clientmessage = " "Return} else {if clientmessage = =" GET "{ret, err: = Redis.  Strings (Redisexec (Rdpool.get (), "Blpop", "screenshot:queue", +)) If Len (ret) = = 2 && err = nil {url: = ret[1]h: = MD5. New () H.write ([]byte (URL)) Name: = Hex. Encodetostring (H.sum (nil)) SubDir: = StrConv. Itoa (time. Now (). Year ()) + PS + StrConv. Itoa (int (time). Now (). Month ())) OS. Mkdirall (Upload_dir+subdir, 0777) Filename_full: = Upload_dir + subdir + PS + nameservermessage = filename_full + "|" + URL PP ("Pop queue OK.", client, servermessage) If Err = Message.send (WS, ServerMessage); Err! = nil {pp ("Could not a Send message to", client, Err. Error ())}} else {p ("Pop queue error.", client, Err. Error ()) If Err = Message.send (WS, "NULL"); Err! = nil {pp ("Could not a Send message to", client, Err. Error ())}}} else if clientmessage = = "Open" {if Err = Message.send (WS, "Open"); Err! = nil {pp ("Could not" Send Message to ", client, Err. Error ())}} else {//todo}clientmessage = ""}}}func Main () {http. Handle ("/socket", WebSocket. Handler (Sockserver)) Err: = http. Listenandserve ("127.0.0.1:9527", nil) if err! = Nil {Panic ("Listenandserve:" + Err. Error ())}}


Phantomjs from a multi-process, do a server-side screenshot service is very simple, the key part of the code is as follows:


var page = require (' webpage '). Create (),    system = require (' System '),    address, output, size;var loop = function () { var ws = new WebSocket ("Ws://127.0.0.1:9527/socket"), Ws.onopen = function (evt) {ws.send (' OPEN ');//ws.send (' GET '); Console.log ("opened."); Ws.onclose = function (evt) {Console.log ("Closed."); Window.settimeout (loop, 60000);}; Ws.onmessage = function (evt) {Console.log ("Message:" + evt.data);//ws.send (evt.data); if (evt.data!= "" && evt.data!= "OPEN") {arr= evt.data.split (' | '); if (arr.length== 2) {name= arr[0]+ ". png"; url= arr[1];screenshot (URL, Name, "");}} Ws.send (' GET ');}; Ws.onerror = function (evt) {Console.log ("Error." + Evt.data);};


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.