Search code examples
javascriptnode.jswebsockethapi.jsnes

Does the Hapi.js websocket protocol communication need to use hapi.js for the client to connect to the websocket?


I am building an API using Hapi. I need WebSocket functionality and it seems that Nes is the most popular to be used with Hapi. This is fine since Nes makes things quite easy, for example, a test route might look as so...

// Register Nes.
await server.register(Nes);
...
...
// WebSocket route.
server.route({
  method: 'GET',
  path: '/h',
  config: {
    id: 'hello',
    handler: (request, h) => {
      return 'world!';
    }
  }
});

This is great, however, the documentation shows that the only way to make a request to this route using WebSockets is by using Nes on the client as well...

const Nes = require('nes');

var client = new Nes.Client('ws://localhost');

const start = async () => {

  await client.connect();
  const payload = await client.request('hello');  // Can also request '/h'
  // payload -> 'world!'
};

start();

My issue is that the client does not use JavaScript. The Nes library does not exist at all. In that case, can I still use WebSockets to make a request to this route? There are no examples of this so I do not understand how I could do so. If it is not possible, then I would like to know what my options are as even Socket.io does not exist in the framework I am using (Flutter).


Solution

  • Since WebSockets are just a protocol, any WebSocket client library for flutter should work. WebSockets are not tied directly to a specific language. Thus, you have to find and implement a WebSocket library for your framework. I browsed their website and found a few potential candidates, though I'm sure it's not an exhaustive list.

    Here are some potential web socket packages from Flutter:

    For information on integrating the package, check out this link here.

    As for developing web sockets with Hapi, you don't have to use NES. It may make the most sense to use a library, like Socket.io that is developed by the same publisher for both the client and server. While using Socket.io with Hapi is beyond the scope of this answer, you may find this medium article helpful.