Hi, I am working on a little project, and my websocket connections seem to be having an issue. Here is the project: https://playcanvas.com/editor/scene/1088199 and I am trying to figure out how to update the position (all the code is made but it will not be tested until this part works) so I need to find out how to make the websocket connection keep from becoming CLOSED (state 3) and CONNECTING (state 0). So far my tests have resulted in those two outcomes and my server code is below (I am pretty sure it works):
const WebSocketServer = require("ws").Server;
const wss = new WebSocketServer({ port: 3000 });
var players = [];
var clients = [];
function Player(id) {
this.id = id;
this.x = 0;
this.y = 0;
this.entity = null;
}
wss.on("connection", (ws) => {
clients.push(ws);
ws.on("message", (data) => {
let json = JSON.parse(data);
switch(json.cmd) {
case "initialize":
var playerId = players.length + 1;
var newPlayer = new Player(playerId);
// Creates a new player object with a unique ID number.
players.push(newPlayer);
// Adds the newly created player to the array.
json = {"cmd":"playerData", "data":{"id": playerId, "players": players}};
ws.send(JSON.stringify(json));
// Sends the connecting client his unique ID, and data about the other players already connected.
json = {"cmd":"playerJoined","data": {"player": newPlayer, "id": playerId}};
wss.clients.forEach(function each(client) {
for(var i = 0; i < clients.length; i++)
{
if(clients[i] != client && client.readyState === ws.OPEN)
client.send(JSON.stringify(json));
}
});
// Sends everyone except the connecting player data about the new player; its also a broadcast function
break;
case "updatePosition":
players[json.id].x = json.x;
players[json.id].y = json.y;
json = {"cmd": "playerMoved", "data": {"x": players[json.id].x, "y": players[json.id].y}};
wss.clients.forEach(function each(client) {
for(var i = 0; i < clients.length; i++)
{
if(clients[i] != client && client.readyState === ws.OPEN)
client.send(JSON.stringify(json));
}
});
//broadcast function; sends data to everyone except the person giving this data
break;
}
});
});
console.log("Server started.");
The server may be active when you view this, so please do not launch the project, it is a hassle to reset the server (yes the server works, I just need to know how to constantly send a websocket message from the client to the server)