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

Deploying Game Server on Heroku

Запись от 8Observer8 размещена 17.02.2019 в 20:58
Показов 1654 Комментарии 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
Комментарии
 
Новые блоги и статьи
Запрет дублирования строк в табличной части
Maks 13.09.2026
Реализация из решения ниже выполнена на нетиповом справочнике "Нормы ТО" с табличной часть "Виды ТО", разработанного в КА2, со следующими реквизитами: - ВидТО (СправочникСсылка. ВидыТО); - ВидГСМ. . .
Скрипты Tampermonkey для CyberForum, ChatGPT, Claude и пр.
Jin X 06.09.2026
Скрипты Tampermonkey для CyberForum, ChatGPT, Claude и пр. Работая с форумом и нейросетями в браузере часто хочется что-то подкорректировать или добавить какого-то функционала. Ниже прикреплён. . .
Программа опроса у.з. расходомера SLS-720F
Argus19 02.09.2026
Программа опроса у. з. расходомера SLS-720F Программа опрашивает один раз в минуту три ультразвуковых расходомера SLS-720F через интерфейс RS-485 по протоколу Modbus RTU. Опрашиваются регистры. . .
Hyper-V: Компьютер должен поддерживать доверенный платформенный модуль 2.0.
Maks 31.08.2026
При установке Windows 11 на виртуальную машину Hyper-V 2-го поколения вылезла такая ошибка: Решение: в параметрах виртуальной машины, в разделе "Безопасность" (Security) активировать флаг. . .
Архитектура биовида Стива в Майнкрафте: Зачем бонобо кубический каннибализм
anaschu 30.08.2026
Кубический Вагинокапитализм в Minecraft: Математический инвариант ОДУ и рок Стивов-бонобо Главная задача разработанной «Модели Всего» — наглядно продемонстрировать наличие системной «судьбы». . .
Оттачиваю умение писать js программы.
russiannick 30.08.2026
Проектом выходного дня стало написание Книги шифров Виженера. Итогом стала версия 200, синий туман. Синий туман назван так, потому что замораживает текст под собой. Нажатие синих кнопок управляют. . .
мат медиц модель 30. презентация проекта
anaschu 27.08.2026
хоп хоп хоп хидахоп, а я кладую))
Как у меня протекала болезнь
zorxor 27.08.2026
Здравствуйте, друзья! Эта запись блога предназначена именно для вас - для моих дорогих друзей, которые знали меня лично. Чтобы ответить на вопрос - а что же со мной произошло на самом деле? Я учился. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru