Ask coding questions

← Back to all posts
WebSocket bound to a domain in node.js
VapinCatCat (0)

I'm trying to make a simple echo WebSocket that is bound to a domain in, but so far, I've been only able to achieve basic results that only depend on localhost:{port}. The result I'm after is ws:// I may have a huge misunderstanding of this topic, all help is appreciated.


const express = require('express');
const socketio = require('');
const http = require('http');

const app = express();
const server = http.Server(app);
const io = socketio(server);


server.listen(3000, () => console.log('server started'));

const connections = [null, null];

io.on('connection', function(socket) {
    socket.on('actuate', function(data) {
19wintersp (1120)

First of all, if you want to just use raw WebSockets (like ""), you need to use a WebSocket library (like ws) instead of Socket.IO. Also, if you want to be able to see a page when you visit the site, you need to add a route for "/", like this (it would go just after app.use...):

// when someone requests to /
app.get("/", function(request, response) {
  // run this function
  // and send the file "index.html"
  response.sendFile(__dirname + "/index.html");

Your current code would work, you would connect with a Socket.IO client, and sending a message in the "actuate" channel would echo the data back.

VapinCatCat (0)

@19wintersp Now what would my WebSocket be called?

VapinCatCat (0)

@19wintersp What would the name of the WebSocket be? Would it be ws:// Im unfamilliar with WebSockets, SORRY!

19wintersp (1120)

@VapinCatCat If you're connecting to the repl, that would work, but I suggest using the secure version ("wss://") instead: "wss://".

VapinCatCat (0)

@19wintersp When I try connecting to the WebSocket, it errors with "undefined"

19wintersp (1120)

@VapinCatCat Are you connecting with SocketIO or a WebSocket?

VapinCatCat (0)

@19wintersp oh, how would I use a websocket instead?.

19wintersp (1120)

@VapinCatCat That's almost perfect, however you should link the WebSocket server to the HTTP server by modifying the constructor to take the HTTP server as an argument:

const wss = new WebSocket.Server({ server: server });

This links the two together.

VapinCatCat (0)


This is what has been happening

VapinCatCat (0)

Im either dumb or it isnt working

19wintersp (1120)

@VapinCatCat Did you update it as per my comment?

VapinCatCat (0)

Heads up, I'm not asking to connect to an external domain, I would like to use the REPL build-in one.