How to establish a webSocket connection to a node

Would really appreciate if someone can point to how a client can establish webSocket connection to a node, and gateway. Any examples would be very helpful.

To illustrate more: say from web-browser, I need to perform things such as:

  • ‘put a block’ onto one IPFS node I am running
  • ‘get back the block’ from the IPFS node I am running
  • ‘list all the blocks’ hosted by my node

I came across ipfs-http-client which establishes a http connection to a gateway and possibly achieve these above - but what I am more interest in knowing is:

  • how to establish a websocket connection (not http connection),
  • and more importantly, how to connect to my IPFS node I am running (instead of / in-addition to connection to public gateway, such as https://ipfs.io etc.)

There are similar question on this forum from others: such as

which does not seem to have an answers, though would really love to have their solutions

Thank you @stebalien

Got it. So you’re trying to connect to the api endpoint using a websocket? Unfortunately, we don’t have support for that. You have to use the HTTP API.

Can I ask why you need a websocket specifically?

Websockets are more effective to achieve reliable messaging on unreliable connections. While HTTP can achieve the results, for the distributed communications we found it more effective to use websockets with message oriented state-machine (SM) models. The moment we start caring for sustained connections, we would have to start throwing-in connection reattempt logic on top of axios or ajax, which is not really worth the effort, when you can get that almost for free with socket.io or its peers.

In other words, websockets give more bang for buck, implementation cost-wise. HTTP for unreliable peers is a joke. Websockets with SM are what we get close to UDP on TCP. HTTP to reliable gateways is a different story.

So, for peer-to-peer communication, we use websockets. However, the HTTP API is generally just supposed to be for local/reliable access. Regardless of what you do, you’ll want to stick some form of authentication out in front of this API.

Personally, I recommend running a separate server that authenticates requests and then forwards them to a local ipfs daemon. You could even use libp2p to communicate with this second server. See: https://github.com/ipfs/go-ipfs/blob/master/docs/experimental-features.md#ipfs-p2p.