0

I'm following a tutorial on how to build a game with WebSockets. However, I don't know how to test my code; it says that localhost doesn't work. Can you explain to me why it's not working? (code)

const http = require("http")
const websocketServer = require("websocket").server
const httpServer = http.createServer();
httpServer.listen(9090, () => console.log("Listrening... on 9090"))
// hashmap
const clients = {}

const wsServer = new websocketServer({
    "httpServer": httpServer
})
wsServer.on("request", request => {
    // connect
    const connection = request.accept(null, request.origin);
    connection.on("open", () => console.log("opened!"))
    connection.on("closed", () => console.log("closed!"))
    connection.on("message", message => {
        const result =  JSON.parse(message.utf8Data)
        // i have recieved a message from the client
        console.log(result)
    })

    // generate a new clientId
    const clientId = guid();
    clients[clientId] = {
        "connection": connection
    }

    const payLoad = {
        "method": "connect",
        "clientId": clientid
    }
    // send back the client connect
    connection.send(JSON.stringify(payLaod))

})



function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1); 
}
 
// then to call it, plus stitch in '4' in the third group
const guid = () => (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();

Thanks for your help! (sorry if this is a stupid question - I'm very new to game dev w/ javascript)

¡Adios!

9
  • what is your browser(client)-side code? that's only a server Commented Nov 1, 2020 at 8:21
  • This looks like server-side code to me, so you can try starting it with node. node yourfile.js if this code is in a file named "yourfile.js". See for instance this article. If this is client-side code, you need to open it in a browser. However, for proper connection with srever, you need to host the page on a webserver locally, and have the server part running as well (locally on another port) that would be the correct test.
    – Pac0
    Commented Nov 1, 2020 at 8:22
  • " it says that localhost doesn't work", what does it say exactly? What is "it"?
    – Pac0
    Commented Nov 1, 2020 at 8:26
  • 1
    @Pac0 I was using visual studio code as my text editor. So pressed start debugging. It took me to localhost:8080. And the screen displayed a message saying: 'This site can't be reached. Localhost refused to connect.' e.t.c Commented Nov 1, 2020 at 8:39
  • 1
    @SiannaZewdie ok, that's very useful. I could therefore recommend to try this guide from the Visual Studio Code site. It should help you get started on how to run a local server running javascript files with node.js.
    – Pac0
    Commented Nov 1, 2020 at 8:44

0

Browse other questions tagged or ask your own question.