Skip to content

Instantly share code, notes, and snippets.

@josephrocca
Last active September 2, 2023 00:11
Show Gist options
  • Save josephrocca/4c476a3250988a56016039d65d2cc142 to your computer and use it in GitHub Desktop.
Save josephrocca/4c476a3250988a56016039d65d2cc142 to your computer and use it in GitHub Desktop.
// For this issue: https://github.com/denoland/deno/issues/20355
// Simple Node.js WebSocket server:
const WebSocket = require('ws'); // npm install ws
const wss = new WebSocket.Server({ port: 8081 });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log(`Received message: ${message.slice(0, 20)}...`);
ws.send('success');
});
});
// Then create a wss tunnel to it with `cloudflared` (it's a one-liner, no account/sign-up needed): https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/
// Just download the `cloudflared` binary and run:
// cloudflared tunnel --url http://localhost:8081
// The server isn't actually relevant for this issue, but you can of course also use Deno with std/http:
// import { serve } from "https://deno.land/std@0.184.0/http/mod.ts";
// serve((req) => {
// if(req.headers.get("upgrade") != "websocket") return new Response(null, { status: 501 });
// const { socket: ws, response } = Deno.upgradeWebSocket(req);
// ws.onmessage = (message) => {
// console.log(`Received message: ${message.slice(0, 20)}...`);
// ws.send('success');
// };
// return response;
// }, { port: 8081 });
// Or use Deno with `npm:ws`:
// const { WebSocketServer } = await import('npm:ws');
// const wss = new WebSocketServer({ port: 8081 });
// wss.on('connection', (ws) => {
// ws.on('message', (message) => {
// console.log(`Received message: ${message.slice(0, 20)}...`);
// ws.send('success');
// });
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment