dir.by  
Поиск >>

Компьютер, программы
→
Node.js (this is a web server that executes JS files)
 Chat (пользователь пишет сообщение и у других появляется сообщение) используя socket.io в Node.js (проект в Visual Studio) 
посмотрели 10093 раз
обновлено: 9 April 2018
Шаг 1) Запускаем Visual Studio 2013 или другую версию (лучше всего Visual Studio 2017)
Шаг 2) Создаем новый проект
Нажимаем в меню: File → New → Project
Выбираем: Other Languages → JavaScript → Node.js → Blank Node.js Web Application
Шаг 3) В файле server.js напишем такой код:
  JavaScript     Файл J:/NodeJsApp1/server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

// load html
app.get('/', function (req, res) {
     res.sendFile(__dirname + '/my.html');
});

// message 'connection'
io.on('connection', function (socket) {
    
     // добавляем user
     Users.Add(socket);
    
     // message 'disconnect'
     socket.on('disconnect', function (msg) {
          Users.Delete(socket); // delete user
     });
    
     // message 'User entered Name'
     socket.on('User entered Name', function (userName) {
          socket.userName = userName;
     });
    
     // message 'add message'
     socket.on('add message', function (text) {
          // send message "user added message" to all users
          io.emit("user added message", { 'name': socket.userName, 'message': text });
     });
});

// web server
var port = process.env.PORT || 1337;
http.listen(port, function () {
     console.log('listening web server');
});

///// my utils /////////
var Users = {
     _sockets: [],// массив socket
    
     Add: function (curSocket) {
          // add user
          this._sockets.push(curSocket);
         
          // LOG!!!
          console.log('user id=' + curSocket.conn.id + ' connected');
     },
    
     Delete: function (curSocket) {
          for (var i = (this._sockets.length - 1); i >= 0; i--) {
               // delete
               if (this._sockets[i] == curSocket)
                    this._sockets.splice(i, 1);
          }
         
          // LOG !!!
          console.log('user id=' + curSocket.conn.id + ' disconnected');
     }
}
Описание файла server.js
Фрагмент кода
Что означает
Файл server.js
io.on('connection', function (socket) {

// добавляем user
Users.Add(socket)
...
});
означает что мы обработаем стандартное событие 'connection'
Обработчиком события является функция
function (socket) {
// добавляем user
Users.Add(socket)
...
}


событие 'connection' вызывется как только в my.html файле вызовется код:
<script>
var socket = io();
</script>
Файл server.js
socket.on('disconnect', function (msg) {
Users.Delete(socket); // delete user
});
означает что мы обработаем стандартное событие 'disconnect'
Обработчиком события является функция
function (msg) {
Users.Delete(socket); // delete user
}


событие 'disconnect' вызывется когда мы закроем страницу или нажмем refresh (перегрузим страницу)
Файл server.js
socket.on('User entered Name', function (userName) {
socket.userName = userName;
});
означает что обработаем мое событие (я ввел свое название) 'User entered Name'
Обработчиком события является функция
function (userName) {
socket.userName = userName;
}


событие 'User entered Name' вызывется как только в my.html файле вызовется код:
<script>
...
socket.emit("User entered Name", elem_userName.value);
...
</script>
Файл server.js
socket.on('add message', function (text) {
// send message "user added message" to all users
io.emit("user added message", { 'name': socket.userName, 'message': text });
});
означает что обработаем мое событие (я ввел свое название) 'add message'
Обработчиком события является функция
function (text) {
// send message "user added message" to all users
io.emit("user added message", { 'name': socket.userName, 'message': text });
}


событие 'add message' вызывется как только в my.html файле вызовется код:
<script>
...
socket.emit("add message", elem.value);
...
</script>
Шаг 4) добавим новый файл my.html
Нажимаем правой клавиши мыши на проекте NodeJsApp1 → Add → New Item → HTML file → my.html
В файле my.html напишем такой код:
  Html     Файл J:/NodeJsApp1/my.html
<html>

<!-- head -->
<head>
<title>My chat</title>
</head>

<!-- body -->
<body>
     <!-- HTML user Name -->
     <div id='SECTION_UserName' style='padding-top:15px;'>
          <div>User name:</div>
          <input type='text' id='elemID_UserName' autofocus />
<input type='submit' value='Ok' onclick='StoreUserName();' style='color:green; font-weight:700;' />
     </div>

     <!-- HTML messages -->
     <div id='SECTION_messages' style='padding-top:15px; display:none;'>
Your message:
<div style='padding-bottom:15px;'>
<textarea type='text' id='myMessage' size='40' rows='4' cols='30'></textarea>
</div>
<input type='submit' value='Add message' onclick='AddMessage();' style='font-weight:700;' />
<div id='messages_history' style='padding-top:15px;'>
</div>
     </div>

<!-- java script -->
<script src="/socket.io/socket.io.js"></script>
<script>
// create socket
var socket = io();

// receive message "user added message"
socket.on('user added message', function (msg) {
// html element
var elem = document.getElementById('messages_history');
elem.innerHTML += '<u>' + msg.name + '</u>' + ': ' + msg.message + '<BR>';
          });
</script>

<script>
function StoreUserName()
{
// html element
var elem_userName = document.getElementById('elemID_UserName');

// send message "User entered Name"
               socket.emit("User entered Name", elem_userName.value);

// show user name
               document.getElementById('SECTION_UserName').innerHTML = "User: " + '<b><font color=green>' + elem_userName.value + '</font></b>';

// show Div with messages
               document.getElementById('SECTION_messages').style.display = "";

// set focus
               document.getElementById('myMessage').focus();
}

function AddMessage() {
// html element
var elem = document.getElementById('myMessage');

// send message "add message"
socket.emit("add message", elem.value);

// clear
elem.value = "";
}
</script>
</body>

</html>
Описание файла my.html
Фрагмент кода
Что означает
Файл my.html
<script>
...
socket.on('user added message', function (msg) {
// html element
var elem = document.getElementById('messages_history');
elem.innerHTML += '<u>' + msg.name + '</u>' + ': ' + msg.message + '<BR>';
});
...
</script>
означает что обработаем мое событие (я ввел свое название) 'user added message'
Обработчиком события является функция
function (msg) {
// html element
var elem = document.getElementById('messages_history');
elem.innerHTML += '<u>' + msg.name + '</u>' + ': ' + msg.message + '<BR>';
}


событие 'user added message' вызывется как только в server.js файле вызовется код:
io.emit("user added message", { 'name': socket.userName, 'message': text });
На заметку!
• серверная функция socket.emit(message, data) отсылает конкретному пользователю data
• серверная функция io.emit(message, data) отсылает всем пользователя data
Шаг 5) добавим express и socket.io пакеты
Нажимаем в меню: Tools → NuGet Package Manager → Package Manager Console
В командной строке пишем:
npm install --save express

ждем и потом пишем:
npm install --save socket.io

Подробнее о добавлении npm пакетов...
Шаг 6) запускаем проект
Нажимаем меню Debug → Start Without Debugging
Открываем еще браузер и вводим web адрес http://localhost:1337
У нас открыто 2 браузера
User Evgen вводит текст и нажимает "Add message"
текст появляется у всех пользователей
 
← Previous topic
Uploading an html file and displaying it on the screen in Node.js (project in Visual Studio)
 
Next topic →
Create https localhost certificate for nodejs
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" Dreame в Беларуси – две недели скидок до 3400 рублей
 
• What is Node.js ?
• How do I find out the version of Node.js?
• Installing Node.js (download and install for Windows)
• How do I update my Node.js version (install the latest version)?
npm in Node.js
• What is npm in Node.js?
• How do I find the npm (Node.js) version?
• How do I update my npm version (install the latest version) ? | Node.js
• File package.json in Node.js
• Difference Between Tilde(~) and Lid(^) in package.json | Node.js
• File package-lock.json in Node.js
• "npm init" | Result: Creates an empty package.json file and populates that file with the default data | Node.js
• "npm install package_name" | Result: Installs JavaScript Library (Package) | For example, run "npm install jquery" | will add the jQuery library to the node_modules folder | Node.js
• "npm install" | Result: Installs the JavaScript libraries (packages) that are specified in the package.json | Node.js
• "npm list -g" (see a list of all installed global packages) | Node.js
• "npm install -g package_name" (global package install) | Node.js
• "npm uninstall -g package_name" (global package removal) | Node.js
• Run "npm run EvgenConvertCSS" | The package.json file like this: "scripts": {"EvgenConvertCSS": "node-sass --include-path scss 1.scss 1.css"} | Node.js
• Run "npm run EvgenMyCommand" | The file package.json like this: "scripts": {"EvgenMyCommand": "mkdir AAA"} | Node.js
• Run "npm run MyScript1" | The file package.json like this: "scripts": {"MyScript1": "npm run MyScript2"} | Node.js
• watch option in npm scripts (watch for changes in files)
Debugging NodeJS
• Debugging Node.js. Looking at variable values, function stack, breakpoints in Visual Studio Code
Writing Node.js application in a text editor (Notepad, Far)
• New Node.js app (create the app in a text editor, run in the console)
• Add the express package to the Node.js (in the Windows console)
• Uploading an html file and displaying it on the screen in Node.js (creating an application in a text editor, launching it in the console)
Using the socket.io module
• A simple application with socket.io in Node.js (creating an application in a text editor, running it in the console)
Writing Node.js project in Visual Studio Code
• New Node.js project (create the project in Visual Studio Code)
• Create a new Node.js project with websocket (create the project in Visual Studio Code) | client & server
Writing Node.js project in Visual Studio
• New Node.js project (create the project in Visual Studio)
• Add the express package to Node.js (in Visual Studio)
• Uploading an html file and displaying it on the screen in Node.js (project in Visual Studio)
• Chat (user writes a message and others get a message) using socket.io in Node.js (project in Visual Studio)
https localhost certificate
• Create https localhost certificate for nodejs
How modules are arranged in Node.js (require, exports)
• What are modules in Node.js ?
• How the require function works inside and what happens when we write require("ModuleName") in Node.js
Creating your own module in Node.js
• Writing and connecting your module to Node.js
Built-in Node.js modules
• "Express" module Node.js !!!!!!!!!!!!
Hosting Node.js on your website
• Hosting and installing Node.js on your website. Configuring Node.js in cPanel
• In Node.js I change the js file, and the old cached js file is displayed. Restart Node.js on your website in cPanel
• Add npm packages to the Node.js on your site (using cPanel)
• Error during WebSocket handshake... Hosting Node.js on your website
Heroku.com free service. Running your Node.js app on Heroku.com
• To use Heroku.com you need to install: Git, Node.js
• Registration on the Heroku.com website
• Installing the command line "Heroku CLI"
• "Heroku CLI" is very slow for Windows
• Running your Node.js app on Heroku.com
WWW sites for learning Node.js
• Sites to learn Node.js

  Ваши вопросы присылайте по почте: info@dir.by