on the hosting installed node, opened port 3000, the port is being listened, when accessing lptf.itSI000 or http://185.53.160.215.32000/ the message Hello Node.js Server! It would seem all is well! but! I want to continue creating a chat, and at the root of the site I create a file (server) with code (example from the Internet, I am new):

var express = require('express'); var app = express(); app.set('port', process.env.PORT || 3000); app.set('host', process.env.HOST || 'localhost'); var logger = require('log4js').getLogger(); var server = require('http').Server(app); var io = require('socket.io')(server); var port = 3000; app.use(express.static('/home/urlyogyj/public_html/views/chat.php')); app.get('/chat.php', function(req,res){ res.sendFile('/home/urlyogyj/public_html/views/chat.php'); }); app.use('/fonts', express.static('/home/urlyogyj/node_modules/uikit/src/fonts/')); app.get('/socket.io.js', function(req,res){ res.sendFile('/home/urlyogyj/node_modules/socket.io-client/dist/socket.io.js'); }); app.get('/jquery.js', function(req,res){ res.sendFile('/home/urlyogyj/node_modules/jquery/dist/jquery.min.js'); }); app.get('/uikit.js', function(req,res){ res.sendFile('/home/urlyogyj/node_modules/uikit/dist/js/uikit.min.js'); }); app.get('/uikit.css', function(req,res){ res.sendFile('/home/urlyogyj/node_modules/uikit/dist/css/uikit.almost-flat.min.css'); }); app.get('/animate.css', function(req,res){ res.sendFile('/home/urlyogyj/node_modules/animate.css/animate.min.css'); }); function usersCountToLog(){ logger.info('User count: '+io.engine.clientsCount); } io.on('connection', function(socket){ function setName(name){ if(name != undefined && name != ''){ socket.session = {}; socket.session.userName = name; socket.session.address = socket.handshake.address; socket.session.id = socket.id; socket.broadcast.emit('newUser', socket.session); socket.emit('userName', socket.session); socket.emit('userList', io.length); logger.info('User '+socket.session.userName+' join from IP: '+socket.session.address); usersCountToLog(); var clients = io.sockets.connected; var clientsList = {} for(var key in clients){ if(clients[key].session) clientsList[key] = clients[key].session; } socket.emit('clientsList', clientsList); console.log(clientsList); } else socket.emit('setName'); } setName(null); socket.on('setName', function(name){ if(name.length > 0) setName(name); else socket.emit('setName'); }); socket.on('message', function(msg){ if(socket.session){ if(socket.session.userName === null || socket.session.userName == '' || socket.session.userName == undefined){ socket.emit('setName'); }else{ logger.trace('-----------'); logger.trace('User: ' + socket.session.userName + ' | Message: ' + msg); logger.trace('====> Sending message to other chaters...'); socket.broadcast.emit('messageFromClients', msg, socket.session.userName); socket.emit('messageToClients', msg, socket.session.userName); } } }); socket.on('disconnect', function(){ if(socket.session){ io.sockets.emit('userDisconnected', socket.session); logger.info('User '+socket.session.userName+' left chat'); usersCountToLog(); } }); }); console.log('server started, tipa...'); 

as you can see by the code I assigned the addresses to the files, they are correct, I restart the server in the console with the command

 node /home/urlyogyj/public_html/app.js screen 

after that, I update the address of lptf.it NO000 and still without changes, displays Hello Node.js Server! I do not understand why, and where and how errors can be tracked. What do I want to achieve: before authorizing any user, the chat is not needed, as soon as the user logs into the site, a socket is opened and the site shows to all other users and guests that the authorized user is online, and a button to create a chat appears opposite his login , but only for authorized users, when you click on it, a chat window opens, like on the Vkontakte or Facebook site, the recipient of the message has a block with a list of all who sent him a message, the recipient clicks on the author and users begin to communicate, each dialogue with the new user must launch his own chat window. and this chat exists on all pages of the site. after the user exits through the exit button or closes the tab, the socket is closed, and all messages are written to the database!

  • dig in the direction of webSocket , Module ws - Dmytryk
  • is it possible in more detail? - vkt
  • Here is almost everything you need here - VoloCorp

1 answer 1

Chat on webSoket . To work, you must install the module ws

html :

  <body> <input type="text" id="chatInput"> <button id="send" type="button">Отправить</button> <script> let chatInput = document.getElementById("chatInput"); let send = document.getElementById("send"); let body = document.querySelector("body"); send.addEventListener("click", sendChatMessage) ws = new WebSocket("ws://localhost:3333"); ws.addEventListener("message", checkChatMessage); function sendChatMessage(event){ var textMessage = chatInput.value; ws.send(textMessage); chatInput.value = ""; } function checkChatMessage(event){ var data = event.data; showChatMessage(data) } function showChatMessage(data){ let tegP = document.createElement("p"); tegP.innerText = data; body.appendChild(tegP) } </script> </body> 

server.js

 const webSocket = require("ws"); const wsPort = 3333; var playerOnline = {}; var wsServer = new webSocket.Server({ port: wsPort }, ()=>{ console.log("**************Сервер Websocket запущен на порту:", wsPort, "**************") }); wsServer.on("connection", (ws, req)=>{ var id = Math.random(); playerOnline[id] = ws; console.log("новое соединение " + id); ws.on('message', function incoming(message) { // console.log('получено сообщение ' + message); for (var key in playerOnline) { playerOnline[key].send(message); } }); ws.on('close', function() { console.log('соединение закрыто ' + id); delete playerOnline[id]; }); }); //эта часть кода отвечает за первоначальное подключение const fs = require("fs"), http = require ("http"), url = require("url"), index = fs.readFileSync('./index.html'),//здесь нужно прописать путь к своему html port = 3000, server = http.createServer(); server.listen(port, function(){ console.log("Сервер запущен по адресу localhost:"+port); console.log("*****************************************************************"); }) server.on("request", function(req, res){ if (req.method == "GET") { res.writeHead(200, {'Content-Type': 'text/html'}); res.end(index) } }) 

;

  • I installed the ws module and started the server in the console. The error Error came: listen EADDRINUSE ::: 3000 at Object._errnoException (util.js: 1003: 13) at _exceptionWithHostPort (util.js: 1024: 20) at Server.setupListenHandle [as _listen2 ] (net.js: 1366: 14) at listenInCluster (net.js: 1407: 12) at Server.listen (net.js: 1495: 7) at Object. <anonymous> (/ home / urlyogyj / public_html / app. js: 38: 8) at Module._compile (module.js: 660: 30) at Object.Module._extensions..js (module.js: 671: 10) at Module.load (module.js: 573: 32) at tryModuleLoad (module.js: 513: 12) - vkt
  • @vkt, EADDRINUSE indicates that the address is busy. - Grundy
  • how busy? I hoster opened port 3000 - vkt
  • Specify another port in the "port" variable or stop the application that is currently occupying port 3000 - Dmytryk