Connect a server and a client with WebSockets in JavaScript

Published November 27, 2020
Advertisement

It is one of the simples way to make real multiplayer because we can host on Heroku. But now we use localhost. Later I will show how to connect the Node.js server (in TypeScript) and Qt C++ client and if you want to see it right now just open and run this example: https://github.com/8Observer8/websocket-connection​ Next is an example in pure JavaScript:

This example shows how to deploy on Heroku: https://github.com/8Observer8/multiplayer-game-in-js
Run it: https://multiplayer-game-in-js.herokuapp.com/

This is locally:

Create this structure:

my-game
---public/index.html
---app.js

  • Install Node.js and “nodemon” (npm i nodemon -g)
  • Go to “my-game” and run: nodemon app.js
  • Open a browser tab and type: localhost:3000
  • Open a browser console: Ctrl+Shift+J and you will see “connection”

app.js (Server)

const express = require("express");
const http = require("http");
const ws = require("ws");
const path = require("path");
 
const app = express();
app.use(express.static(path.join(__dirname, "./public")));
app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "index.html")) });
 
const httpServer = http.createServer(app);
const wss = new ws.Server({ server: httpServer });
wss.on("connection", (wss) => { console.log("connected") });
 
const port = process.env.PORT || 3000;
httpServer.listen(port, () => { console.log("Server started. Port: ", port) });

public/index.html (Client)

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <h1>Hello</h1>
    <script>
        const ws = new WebSocket("ws://localhost:3000");
        ws.onopen =
            () => {
                console.log("connected");
            }
    </script>
</body>
 
</html>
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement