Reputation: 61
I am trying to make a websocket client in a chrome extension that will listen for open websocket servers. Once one is open, it will connect and perform its task. How do I set it so that the client will start listening right after disconnection?
This is the code I have to connect, but I have no idea how to make it into a listener.
function connect(host) {
var ws = new WebSocket(host);
ws.onopen = function () {
alert('connected');
connection = true;
};
ws.onmessage = function (evt, tab) {
if(evt.data == "connect"){
rpwd = 'hello ws';
ports[curTabID].postMessage({text: rpwd});
}
};
ws.onclose = function () {
alert('socket closed');
connection = false;
webConnect('ws://localhost:8080');
};
};
Upvotes: 3
Views: 10628
Reputation: 76
It doesn't seem like a browser has any way of listening for connections using WebSockets. Everything I have read including the documentation for socket.io point to node.js being the only JavaScript way of listening, or providing server sockets.
Upvotes: 0
Reputation: 77523
Unfortunately, you can't easily do it.
1) Standard API, WebSocket
, is only a client, nothing you can do about that. The browser is not supposed to be a server.
2) Extensions are supposed to augment the browser functionality, so chrome
APIs can possibly help. Unfortunately, in case of extensions the answer is still no.
3) For Chrome apps, however, it is possible. There is a chrome.sockets.tcpServer
API, but of course no bundled server implementations. You would have to either implement a web+ws server yourself, or use one of the existing solutions like this one.
That aside, are you sure you really want a WS server? You said it's to "listen for open servers" - how would servers make their presence known? Wouldn't it be more logical to just poll them periodically to see if they are open?
Upvotes: 2