简体   繁体   中英

websocket client discovering server

I am in a situation where I want my websocket client to connect to server but server ip or dns name is unknown. Both client and server are in local network(connected to same router). I tried something like this....

var socket;
for(var i=1; i<255; i++) {
  socket = new WebSocket('ws://192.168.1.'+i+':8080/service');

  socket.onopen = function () {   
    console.log('WebSocket Connected!!');   
  };

  socket.onclose = function (event) {
    console.log('WebSocket Disconnected!!');
    socket.close();
  };

  socket.onmessage = function (event) {
    console.log('WebSocket receive msg: ' + event.data);
  }
}

This works but I am not sure if I am doing it right or if there is a better way to do it. Any help is appreciated.

Have you tried hooking up an onerror listener to see what errors are being thrown? It's possible that you're finding the server but that some mis-configuration in the server is causing it to error out before the connection is opened.

WebSockets is still a very actively evolving standard. There are multiple drafts out there and some browsers support some drafts but not others. Old drafts are often considered insecure, so some browsers don't support them, while other browsers only support the old drafts because they haven't been updated for the newer ones. Also, servers may be in the same boat. It's kind of the wild west.

I suggest putting in robust error handling and also fallback when things aren't working right. Packages like Socket.io offer this kind of transparent fallback support. I suggest checking that out if you're looking for a quick solution. However, if you're just using this as a learning experience (and I encourage such behavior!), you will want to hook up an onerror handler to see what's going on and why each connection fails.

This solution would of course scale horribly when you deploy on a network larger than class A. And when there is more than one websocket server on the network, you wouldn't know which one to hit.

But as long as there is no DNS and no static IP addresses on your network, port-scanning the whole IP range is the only way to find the server.

Are you sure it's impossible to assign a static IP address to the server machine? Most consumer grade routers don't strictly enforce the use of DHCP and usually it's not a problem when only some machines are configured with static IP addresses. Some router firmwares also allow to configure the DHCP server to always assign the same IP address to specific MAC addresses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM