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

Socket.io Connection, JS/ES5

Запись от 8Observer8 размещена 15.02.2019 в 17:59
Показов 1798 Комментарии 1
Метки javascript, socket.io

Blog content

I will try to explain a process in step-by-step how to prepare server but it will be good if you will watch this video tutorial in parallel: Setup & Sending Files. Node.js Tutorial Guide
Youtube


You need to download and install Node.js: https://nodejs.org/en/download/

At first test let's create a very simple server script locally that will write in the console terminal*"client connected" when client will be connected to the server.

Create a folder for your project and go to the folder using CMD. Write this command in the console terminale to create package.json:
npm init -y
Install "socket.io" and "express" to a local "node_modules" folder. Enter the command for this:
npm install --save socket.io express
Now we are ready to write a simple server script and a client script. I use VSCode editor: https://code.visualstudio.com/

Open your prefered code editor. If you use VSCode you can run in the console terminal this command from your project folder:
code .
Create two folders in your project: "server" and "client". Create the "server.js" file in the "server" folder. Create the "client.js" file in the "client" folder. Create the "index.html" file in the "client" folder.

index.html

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!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">
    <title>Multiplayer Snake</title>
</head>
 
<body>
    <h1>Hello, World</h1>
</body>
 
</html>
Create the file: "app.js" in the root of your project:

app.js

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
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 = 8080;
server.listen(port);
console.log("Server started. Port = " + port);
You can run this script from the console terminal by the command:

node app.js
You will see a message in the console:

Server started. Port = 8080
Write the address in the browser: localhost:8080

You will see "Hello, World" on the web page.

Let's find "cnd socket.io" url in the Internet. Add this code to the index.html:

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!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>
    <h1>Hello, World</h1>
    <script>
        var socket = io();
    </script>
</body>
 
</html>
Create a socket callback in app.js:

app.js

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 = 8080;
server.listen(port);
console.log("Server started. Port = " + port);
 
var io = require("socket.io")(server, {});
 
io.sockets.on("connection", function(socket)
{
    console.log("socket connection");
});
Run the server:

node app.js
Write the address in the browser: localhost:8080

You will see the message "socket connection" in the console.
Метки javascript, socket.io
Размещено в Без категории
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Всего комментариев 1
Комментарии
  1. Старый комментарий
    Запись от 8Observer8 размещена 17.02.2019 в 19:29 8Observer8 на форуме
 
Новые блоги и статьи
сукцессия 29. Переход от одних деревьев на другие делать более или менее вероятностным?
anaschu 12.07.2026
Насколько смена типов микоризы — исключительное событие в двухвековой сукцессии? Оценка вероятности в пространстве параметров В текущей версии модели успешно реализован ключевой механизм. . .
сукцессия 27. Думаю, как переделывать уже написанную статью с планами на сукцессию.
anaschu 12.07.2026
Анализ соответствия модели требованиям Реализованные компоненты: Механизм закисления почвы через протонную помпу Конкуренция между типами микориз pH как триггер сукцессии C/ P соотношение. . .
Сукцессия 26. Мат модель создана.
anaschu 12.07.2026
Модель смены растительных сукцессий посредством управления грибами работает внутри небольшой ячейки почвы, восстанавливающейся после пожара, где ненадолго бывшее царство хвойных снова захватили. . .
Решил проблему с ошибкой пагинации сообщений с сервера на алгоритме обхода дерева "Эстафета хвоста".
Hrethgir 12.07.2026
Проблема была в том, что удалялась именно новая кнопка, а не старая. Ни один ИИ не обнаружил это, а сам я смог только когда с работой стало попроще и когда заставил работать будущее автономное. . .
сукцессия 25. Хронология ошибок
anaschu 12.07.2026
# От 50-тонного гриба до устойчивого леса: хроника ошибок при построении модели вековой сукцессии микоризы ## О чём эта статья В процессе построения ОДУ-модели (система дифференциальных. . .
сукцессия 24. Промежуточное общее описание модели
anaschu 12.07.2026
Хендофф: модель АМ→ЭКМ сукцессии микоризы (ризосфера, 50 лет) Содержание проекта Симуляция вековой (50 лет) экологической сукцессии в почве леса Основные участники: АМ-гриб, ЭКМ-гриб,. . .
сукцессия 23. Более физиологичная физиология, более экологичная экология, более диффурные диффуры.
anaschu 12.07.2026
Что реально нашли и починили за эти 5 часов Правило Линдемана (КПД конверсии сахара в тело, kEff) — раньше 100% полученного углерода шло прямо в биомассу гриба; теперь только kEff=0. 5 (после. . .
сукцессия 22. От артефактов к физиологии: калибровка агентной модели грибной сукцессии для воспроизведения сезонной динамики и pH-плато
anaschu 11.07.2026
Аннотация В данной работе представлена калибровка агентной модели динамики грибных сообществ (fungal-succession), направленная на устранение нефизичных артефактов (коллапс биомассы, мгновенное. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru