Here is the nodejs server code:

var net = require("net"); var clientPeopleSockets = []; var serverPort = 8124; var idClientPeople = 1000000000; var server = net.createServer(function(socket) { //генерация ид пользователей idClientPeople = idClientPeople +1; //присваивание ид сокету socket.socketId = idClientPeople; clientPeopleSockets.push(socket); console.log('Клиент подключился id: '+idClientPeople); socket.on('data', function (data) { //убираем всякие переносы сторки и т.д могут быть ошибки криво все var dataClient = data.toString('utf8'); dataClientNew = dataClient.replace(/[\r\n]/m,'');//***************** del dataClientNew = dataClientNew.substring(0, dataClient.length - 1);//********** del var coordMouse = dataClientNew.substr(0,5);//************ del var commandItString = dataClient.split(','); //вывод объекта в консоль console.log(JSON.stringify(data, null, 4)); //jsonDate = JSON.stringify(data, null, 4); //console.log(jsonDate); //----------------------------------------------------------------- if (commandItString[0] == '100') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == idClientPeople) { clientPeopleSockets[i].write(clientPeopleSockets[i].socketId+'\n'); } } } else if (commandItString[0] == '101') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].remouteUserId = idClientPeople; //ид пользователя суппорт записывается в объект пользователя к которому подключаются console.log('id: '+clientPeopleSockets[i].socketId+'--> '+' remouteUserId: '+clientPeopleSockets[i].remouteUserId); } } } //test------------------------------------------------ else if (commandItString[0] == '102') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].write('102'+commandItString[2]+'\n'); } } } else if (commandItString[0] == '103') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].write('103'+commandItString[2]+'\n'); } } } else if (commandItString[0] == '104') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].write('104'+commandItString[2]+'\n'); } } } else if (commandItString[0] == '105') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].write('105'+commandItString[2]+'\n'); } } } else if (commandItString[0] == '106') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].write('106'+commandItString[2]+'\n'); } } } else if (commandItString[0] == '107') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].write('107'+commandItString[2]+'\n'); } } } else if (commandItString[0] == '108') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].write('108'+commandItString[2]+'\n'); } } } else if (commandItString[0] == '109') { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == commandItString[1]) { clientPeopleSockets[i].write('109'+commandItString[2]+'\n'); } } } else { for(i=0; i<clientPeopleSockets.length; i++) { if (clientPeopleSockets[i].socketId == '1000000002') { clientPeopleSockets[i].write(data); } } } //---------------------------------------------- }); socket.on('end', function () { var i = clientPeopleSockets.indexOf(socket); clientPeopleSockets.splice(i, 1); }); }); server.listen(serverPort, function() { console.log('Сервер запущен на порту '+serverPort); }); 

Clients from the application connect to this server and exchange data. You need to add data retrieval from the application to the browser. Tell me how can this be implemented correctly? On socket.io, you can somehow get it if yes, throw a small example. Or maybe through a browser you can connect directly to tcp / ip?

  • one
    This question does not apply, but I would advise you to get rid of these if else , get an action object for the place of this and write down the behavior, the key will be equal to the command id, and then it is easy to use action[commandIdString]() , it will be much better - ThisMan
  • ok, i will surely fix this test code ... check if it will work at all) - JohnLemon September

1 answer 1

Choose the most pleasant way for you:

1. Router - easier ( https://www.npmjs.com/package/router#api )

On the server, npm install router : npm install router

 router.get('/', function (req, res) { res.end('индекс'); }); router.get('/путь1', function (req, res) { res.end('данные1'); }); 

On the client, simply send a request to myserver.com/путь1 , in the window will display the данные1

2. Socket.io - harder ( http://socket.io/docs/# )

On the server, npm install socket.io :

 var io = require('socket.io')(app); io.on('connection', function (socket) { socket.on('data', function (data,sendBack) { ...//какие-то вычисления sendback(123); //возвращаем данные } } 

On the client, download and connect the socket.io.js script, then do:

 var socket = io('http://localhost'); socket.emit('data',data,funciton(dataBack){ //получаем данные от сервера console.log("Сервер вернул:",dataBack); //выведет 123 }) 

You set the number of arguments for sendBack yourself, it is important that the client takes the same callback. For example, in NodeJS, they often send errors as the first argument, and as the second, data packed into an array or object.

  • Hmm ... that is, the code is approximately on the server, and which libraries to connect to the HTML page) on the client? ) Or should it also be located on the server? and how to connect)? Actually there are a lot of questions as I only understand more in the node .... - JohnLemon
  • socket.io/docs/# - Mi Ke Bu
  • Can you at least briefly describe for a beginner what should be? - JohnLemon
  • that is, through socket.io can I connect boldly? or on the server I also have to turn on socket.io if this is the case, then my applications will stop working because they do not know how to work with socket.io correctly? - JohnLemon
  • Yes, you can safely. Added in the answer a few details for a beginner. And I advise you to try code examples from their documentation) - Mi Ke Bu