Canatron
Canatron

Reputation: 85

400 bad request (making game with node and socket.io)

Making a game, I have no idea what I am doing when it comes to the online aspect.

I am using node.js using my computer as the server host and client (localhost:3000)

var express = require('express'); //no idea what I am doing here
var app = express();
var server = app.listen(3000);
var socket = require("socket.io");
var io = socket(server);
io.sockets.on('connection', newConnection);
app.use(express.static("public"));

console.log("server is up"); //tells me that the server is ready

function newConnection(socket) {
    console.log("new player!", socket.id); //tells me when a new player connects.
}

also have this code within the main public javascript file

var socket;
socket = io.connect("localhost:3000");

Whenever a new player connects i get 400 bad request errors and the game thinks multiple players have joined.

picture to aid

so pls help.

Upvotes: 0

Views: 523

Answers (2)

Canatron
Canatron

Reputation: 85

In my game, I had a constructor function called "Number" and that was causing the problem the entire time.

I'm assuming that the socket.io or node.js already had a function called "Number" and that's what caused the problem.

Upvotes: 0

Anurag Awasthi
Anurag Awasthi

Reputation: 6233

You will need to handle what happens when someone connects to your server.

var express = require('express');
var app = express();
var server = require("http").createServer(app);
server.listen(3000)  //server listens on port 3000
var io = require("socket.io")(server)

//this will be called when a new client connects
io.on("connection", (socket)=>{
   //socket is the socket object of the new client
   console.log("new socket connected with socket id = " + socket.id)

})

Look at socket.io docs for more info.

Upvotes: 1

Related Questions