lukeed / sockette

The cutest little WebSocket wrapper! 🧦
MIT License
2.45k stars 81 forks source link

Access underlying socket object #43

Closed evanshortiss closed 5 years ago

evanshortiss commented 5 years ago

In an application I'm working on I'd like to check that the socket has flushed data. This can be done using socket.bufferedAmount according to this SO post

Could this library support a function to check this, or simply expose the underlying socket object for these use cases, e.g:

const ws = new Sockette('ws://localhost:3000', {
  timeout: 5e3,
  maxAttempts: 10,
  onopen: e => console.log('Connected!', e),
  onmessage: e => console.log('Received:', e),
  onreconnect: e => console.log('Reconnecting...', e),
  onmaximum: e => console.log('Stop Attempting!', e),
  onclose: e => console.log('Closed!', e),
  onerror: e => console.log('Error:', e)
});

// access underlying socket
ws.socket.bufferedAmount
lukeed commented 5 years ago

Hey, you were so close 😉

The underlying socket is available to any & all event handlers. The WebSocket is an event emitter, so the current, up-to-date WebSocket instance is always available as ev.target. You can save that reference and do whatever you'd like with it!

There are a few examples scattered across the issues; https://github.com/lukeed/sockette/issues/12#issuecomment-365170978, https://github.com/lukeed/sockette/issues/31#issuecomment-406741545, and https://github.com/lukeed/sockette/issues/18

Hope that helps!

evanshortiss commented 5 years ago

Man I need to RTFM next time and not just the Example code. Thanks! 👍

lukeed commented 5 years ago

No worries!