0

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

EDIT 2 : I changed my code a little and i used process.env.PORT but it says the port is already used(because its the port of the website) i saw somewhere that the legal port for https is 443 and for http is 80 but i couldnt use 8080 or 80 or 443 due to this error

AlirezaBest
  • 103
  • 7

1 Answers1

0

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);
}
IT goldman
  • 14,885
  • 2
  • 14
  • 28