Skip to content

Vexcited/tcp-websocket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tcp-websocket

Was originally made to resolve this Bun issue: oven-sh/bun#4529 (still not fixed)

Instead of using node:http or node:https, we use plain TCP sockets to communicate, even for the HTTP request handshake.

Bun support is main priority but it should also support Node. Even though the Node support is kind of experimental.

Getting started

bun add tcp-websocket
import TCPWebSocket from "tcp-websocket";

const ws = new TCPWebSocket("wss://ws.postman-echo.com/raw");

ws.on("open", () => {
  console.info("[open]: connected !\n");
  
  const data = "hello world!";
  ws.send(data);
  console.info("[send::message]:", data);
});

ws.once("message", (event) => {
  console.info("[receive::message]:", event.data);

  console.info("\n[info]: will close in 5 seconds...");
  setTimeout(() => ws.close(), 5_000)
});

ws.on("close", (event) => {
  console.info(`[close(${event.code})]: ${event.reason || "[no reason provided]"}`)
});

You can find more examples @ ./examples.

API

Warning: TCPWebSocket class is not fully compatible with the WebSocket interface, yet.

Why not use those libraries ?

Packages using node:http or node:https to make the request handshake will fail in Bun since their implementation is kinda broken.

Package name on NPM Issues with Bun
ws Uses the node:http and node:https to make the request handshake. Source
websocket Uses the node:http and node:https to make the request handshake. Source
websocket-stream Uses the ws package internally, see ws. Source
undici Uses http2 under the hood which is currently not implemented in Bun. Source
websocket-driver Works with Bun, but last update was 3 years ago with no TS declarations and ES5 syntax. This package reuses a lot of code from this package.

Development

git clone https://github.com/Vexcited/tcp-websocket

# Install dependencies
bun install

The main source code is located in ./src/index.ts.

You can run the main examples located in ./src/examples using bun run ./examples/simple.ts, for example.

Credits

Resources