skip to Main Content

I made a websocket server in my host in <www.example.com> but the client doesnt connect to it.
Here is the code :
Server.js :

const ws = new require('ws');
const wss = new ws.Server({noServer: true});
const http = require('http');
const express = require("express");
const app = express();
app.get("/multiplayerChat2/",(req,res) => {
    wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onSocketConnect);
});
http.createServer(app).listen();
function onSocketConnect(ws){
    console.log("hello")
  ws.on('message', function(message) {
    message = message.slice(0, 50); // max message length will be 50
    wss.clients.forEach(function(client){
        client.send(message.toString("utf8"));  
    })
  });
}

Client js :

let socket = new WebSocket("wss://example.com/multiplayerChat2/");
socket.onerror = (err) => {
  console.log("websocket error : ",err);
}
// send message from the form
document.forms.publish.onsubmit = function() {
  let outgoingMessage = this.message.value;
  socket.send(outgoingMessage);
  return false;
};

// message received - show the message in div#messages
socket.onmessage = function(event) {
  let message = event.data;

  let messageElem = document.createElement('div');
  messageElem.textContent = message;
  document.getElementById('messages').prepend(messageElem);
}

Client html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form name="publish">
        <input type="text" id="message">
        <input type="submit" value="Send">
    </form>
    <div id="messages"></div>
</body>
<script src="index.js"></script>
</html>

Note that the server.js file is in <example.com/multiplayerChat2>.
I made some changes on the websocket connection url but websocket connection gives this error :

WebSocket connection to 'wss://example.com/multiplayerChat2/' failed: 

EDIT : ok i think this is a little bit hard but at least say how can i make a websocket server without handling http requests but its origin be in the website

2

Answers


  1. It appears the issue is due to how you’re setting up the WebSocket Server and the HTTP server. In your code, you’re using the http.createServer(app).listen(); function without specifying a port. Moreover, you’re creating an instance of a WebSocket server (wss) and an HTTP server separately, but they aren’t linked.
    this is a simple code:

    const express = require('express');
    const http = require('http');
    const WebSocket = require('ws');
    
    const app = express();
    const server = http.createServer(app);
    
    const wss = new WebSocket.Server({ server });
    
    app.get("/multiplayerChat2/", (req, res) => {
        res.send('WebSocket endpoint');
    });
    
    wss.on('connection', function connection(ws) {
        console.log("hello");
        ws.on('message', function incoming(message) {
            message = message.slice(0, 50); // max message length will be 50
            wss.clients.forEach(function each(client) {
                if (client.readyState === WebSocket.OPEN) {
                    client.send(message.toString("utf8"));
                }
            });
        });
    });
    
    const port = process.env.PORT || 3000; // Please specify a valid port
    server.listen(port, () => {
        console.log(`Server started on port ${port}`);
    });
    

    With this setup, both the WebSocket and the HTTP server are running on the same port. Also, now, the WebSocket server is properly attached to the HTTP server.

    Now in your client, you can create a WebSocket connection with wss://example.com:port/multiplayerChat2/.

    Login or Signup to reply.
  2. you can’t open http server and connect with wss://. it needs to be https with specifying the absolute path of the certificate.

    var server
    var is_ssl = true;
    if (is_ssl) {
      var httpsOptions = {
        key: fs.readFileSync(process.env.SSL_KEY_FILE),
        cert: fs.readFileSync(process.env.SSL_CERT_FILE)
      };
      server = require('https').createServer(httpsOptions, app);
    } else {
      server = require('http').createServer(app);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search