نمونه برنامه ارتباط کلاینت و سرور در node.js
دوشنبه, ۲۴ خرداد ۱۳۹۵، ۰۸:۳۳ ب.ظ
node.js
TCP Server and Client
برنامه سرور ( server.js )
var net = require('net'); var HOST = '127.0.0.1'; var PORT = 6969; // Create a server instance, and chain the listen function to it // The function passed to net.createServer() becomes the event handler for the 'connection' event // The sock object the callback function receives UNIQUE for each connection net.createServer(function(sock) { // We have a connection - a socket object is assigned to the connection automatically console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort); // Add a 'data' event handler to this instance of socket sock.on('data', function(data) { console.log('DATA ' + sock.remoteAddress + ': ' + data); // Write the data back to the socket, the client will receive it as data from the server sock.write('You said "' + data + '"'); }); // Add a 'close' event handler to this instance of socket sock.on('close', function(data) { console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort); }); }).listen(PORT, HOST); console.log('Server listening on ' + HOST +':'+ PORT);
برنامه کلاینت ( client.js )
var net = require('net'); var HOST = '127.0.0.1'; var PORT = 6969; var client = new net.Socket(); client.connect(PORT, HOST, function() { console.log('CONNECTED TO: ' + HOST + ':' + PORT); // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client client.write('I am Benyamin'); }); // Add a 'data' event handler for the client socket // data is what the server sent to this socket client.on('data', function(data) { console.log('DATA: ' + data); // Close the client socket completely client.destroy(); }); // Add a 'close' event handler for the client socket client.on('close', function() { console.log('Connection closed'); });
برای اجرا در Command Prompt اپتدا سرور را اجرا میکنیم سپس برنامه کلاینت ( باید با دستور cd به پوشه ای که این 2 برنامه رو ذخیره کردید برید )
node server.js
حال یک Command Prompt دیگر باز می کنیم
node client.js
در مثال بالا پیام هایی بین سرور و کلاینت ارسال می شود
۹۵/۰۳/۲۴