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
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:
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/
.you can’t open
http
server and connect withwss://
. it needs to behttps
with specifying the absolute path of the certificate.