3

I need to send websocket calls from webworkers, how can i get it. I dont think so is there any support from the user agents. if support available please give me an example to do this.

sample stuff what I am trying.

var ws = new WebSocket(url);
var worker=new Worker(worker.js);

ws.onmessage=function(e){
worker.postMessage({ws:ws,data:e.data});
}

worker.js

onmessage=function(e){
  var ws=e.data.ws;
  var data=e.data.data;
  var request=someProcess(data);

  ws.send(request);
}
kirankumar
  • 191
  • 1
  • 2
  • 13

1 Answers1

2

In the worker ws is a string deserialized JSON object, not a WebSocket object. You can't pass objects with methods to workers which means the worker will need to reply to the main thread and the main thread does the ws.send(worker_response).

I suspect the error you are getting is a DATA_CLONE_ERR exception or similar due to WebSocket objects not being JSON serializable through the structured clone algorithm.

SpliFF
  • 38,186
  • 16
  • 91
  • 120
  • From this discussion(http://stackoverflow.com/questions/10886910/how-to-maintain-a-websockets-connection-between-pages). I got comment "you can use WebSockets via Web Workers in Chrome and there is a Mozilla bug to implement support for this in Firefox: bugzilla.mozilla.org/show_bug.cgi?id=504553 – kanaka ". Then say can,t we send requests from worker to websockets. – kirankumar Aug 08 '12 at 10:12
  • I agree with you but I have doubt that is it really possible to send requests or not – kirankumar Aug 08 '12 at 10:16
  • 1
    This isn't about whether you can use websocket inside a worker. What I meant was the object `e.data.ws` is *NOT a websocket object* and therefore has no `send()` method. So what is `e.data.ws`? It's a deserialized JSON object that was created from the WebSocket object but contains no functions per the note under JSON data @ https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers . Specifically: "Objects passed in and out of workers must not contain functions or cyclical references, since JSON doesn't support these." – SpliFF Aug 15 '12 at 05:51
  • 1
    Can't you just keep the whole `websocket` only inside the webworker in the first place? And then just pass the `websocket` action (chat, whatever) as json back into jQuery? Would this be possible? – knutole Jan 08 '13 at 09:29
  • I thought WebSocket, Indexeddb, XMLHttpRequest, and some other APIs were accessible to workers??? – Cody Jan 14 '14 at 20:54
  • @Cody: This question dates to 2012, what is possible on browsers/devices in 2014 or beyond is another question. – SpliFF May 01 '14 at 04:03
  • 1
    UPDATE: May 12, 2015 Firefox 38 allows for WebSockets in Web Workers. – pcunite Jul 07 '15 at 20:26