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

Socket.io Connection, JS/ES5

Запись от 8Observer8 размещена 15.02.2019 в 17:59
Показов 1823 Комментарии 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 на форуме
 
Новые блоги и статьи
Скрипты 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
Здравствуйте, друзья! Эта запись блога предназначена именно для вас - для моих дорогих друзей, которые знали меня лично. Чтобы ответить на вопрос - а что же со мной произошло на самом деле? Я учился. . .
Нашел вот забавное видео о измерениях. Лучшее что я видел на эту тему
kumehtar 26.08.2026
ILETXiw9bMQ Основная суть и тезисы по измерениям: 0D (Нулевое измерение): точка, не имеющая длины, ширины, высоты или объема. Объект не может перемещаться в 0D. 1D (Первое измерение):. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru