Форум программистов, компьютерный форум, киберфорум
8Observer8
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  

Deploying Game Server on Heroku

Запись от 8Observer8 размещена 17.02.2019 в 20:58
Показов 1631 Комментарии 0
Метки gamedev, heroku, javascript

Blog content

Heroku is a free hosting. Let's deploy the application from this instruction: Emit and Broadcast JSON using Socket.io and JS/ES5

You need to register on https://heroku.com/ and complete this official instruction: Getting Started on Heroku with Node.js

Go here: https://dashboard.heroku.com/apps and create a new application. For this you need to press "New" button in right top corner. Select "create new app". I created a new application with the name: red-game. It this case my application will be available from this domain: https://red-game.herokuapp.com/ When you create your application at first time you will see this web page:

Heroku | Welcome to your new app!

Refer to the documentation if you need help deploying.
Go to your work folder using the console terminal. You need to have the file "app.js" and and "client" folder in your work folder. Indeside "client" folder you need to have "index.html" from the instruction above. But we will change a few lines in "app.js". We will change a port number.

Replace this line of code:
JavaScript
1
var port = 8080;
On this line:

JavaScript
1
var port = process.env.PORT || 3000;
Note. If you do not want to read the previous instruction you can just copy-past this files and install packages using this commands:
npm init -y
npm install --save express socket.io shortid
app.js

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var express = require("express");
var app = express();
var server = require("http").Server(app);
 
app.get("/", function(req, res)
{
    res.sendFile(__dirname + "/client/index.html");
});
app.use("/client", express.static(__dirname + "/client"));
 
var port = process.env.PORT || 3000;
server.listen(port);
console.log("Server started. Port = " + port);
 
var io = require("socket.io")(server, {});
var shortid = require('shortid');
 
io.sockets.on("connection", function(socket)
{
    var clientName = shortid.generate();
    console.log("client was connected, name = " + clientName);
 
    socket.on("getMyName", function()
    {
        socket.emit("onGetMyName", { name: clientName });
    });
 
    socket.on("sendMyNameToAllClients", function()
    {
        socket.broadcast.emit("onSendMyNameToAllClients", { name: clientName });
        console.log(clientName);
    });
});
index.html

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <title>Multiplayer Snake</title>
</head>
 
<body>
    <button onclick="getMyName();">Get My Name</button>
    <button onclick="sendMyNameToAllClients();">Send my Name to all Clients</button>
    <script>
        var socket = io();
 
        socket.emit("hello", { message: "hello from client!" });
 
        socket.on("onGetMyName", function(data)
        {
            console.log("My Name: " + data.name);
        });
 
        socket.on("onSendMyNameToAllClients", function(data)
        {
            console.log("Name of another client: " + data.name);
        });
 
        function getMyName()
        {
            socket.emit("getMyName");
        }
 
        function sendMyNameToAllClients()
        {
            socket.emit("sendMyNameToAllClients");
        }
    </script>
</body>
 
</html>
Add a new file: .gitignore (pay attention, "." is a part of the name)

The file ".gitignore" should have this*content:
/node_modules/
Add the start script command in package.json here:
JavaScript
1
2
3
4
    "scripts": {
        "start": "app.js",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
Enter these commands in the command terminal. Pay attention: you need to write your application name instead of "red-game":

heroku login
git init
heroku git:remote -a red-game
Now we can to add new files, commit them and push/deploy our application on Heroku.

Enter these commands:

git commit -am "First commit"
git push heroku master
Go to your application in the browser. For example, in my case: https://red-game.herokuapp.com/ Open the browser console, for example in Chrome: "Ctrl+Shift+J". Click on buttons and you will see messages in the browser console. Open two tabs and press "Send my Name to all Clients" button. You will see a messages in the console in the second client tab.

P.S. You need to empty cache when you change your client side scripts of files: RMB on "Reload" button and select "Empty Cache and Hard Reload"
Метки gamedev, heroku, javascript
Размещено в Без категории
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Всего комментариев 0
Комментарии
 
Новые блоги и статьи
Часы электронные
Uhbif79 12.08.2026
Выкладываю программу часов. Программа позволяет: 1. Использовать системное время и дату, 2. Есть возможность вводить время и дату вручную. 3. Реализованы 2 будильника: начало и конец рабочего дня. . . .
Часы с будильником на основе класса QLCDNumber
Uhbif79 12.08.2026
Всем добрый день, выкладываю программу часов с будильником на основе класса QLCDNumber. Здесь я пробовал самостоятельно создавал классы, впервые столкнулся с видимостью переменной одного класса из. . .
Установка MinGW GCC 16.2 и CMake
8Observer8 10.08.2026
VK Видео: https:/ / vkvideo. ru/ video-240781534_456239017 YouTube: eY5-5PyI9NM Текстовая версия
Неделя из жизни имитационной модели склада: мои кривые руки растут, откуда надо
anaschu 10.08.2026
Неделя из жизни имитационной модели склада: как я почти написал неправильную логику и что с этим делать Работаю сейчас над учебно-рабочим проектом: строю в AnyLogic имитационную модель процессов. . .
Калькулятор для расчета родства
russiannick 07.08.2026
1. Задача: Создать калькулятор для расчета родства. Родственных связей существует 8 ступеней, такие как: p - отец P - мать q - муж Q - жена b - брат B - сестра s - сын S - дочь
Мир по моей воле
kumehtar 07.08.2026
Когда-то кажется, что всё просто. Ты весь такой светлый. Причиняешь добро. Борешься за справедливость в этом тёмном мире. Потом начинаешь замечать одну неприятную вещь. Почти каждый хороший. . .
Кредитный калькулятор
Maks 05.08.2026
Решение задачи по прикладной информатике средствами 1С. Задача: Напишите приложение-калькулятор, которое помогает рассчитывать параметры кредита для аннуитетного и дифференцированного видов. . .
У нас сейчас поговорку "Опять 25" нужно переделать на "Опять +35".
kumehtar 04.08.2026
С ностальгией вспоминаю времена моего детства, когда у нас и правда +25 - была максимальная температура летом. Раньше +25 °C реально казались вершиной жары, когда можно было весь день пропадать на. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru