ارسال پیام بین کلاینت و سرور ( چت ساده )
چهارشنبه, ۲۶ خرداد ۱۳۹۵، ۱۰:۴۰ ب.ظ
node.js
Chat 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 // Ersal matn az server ber client const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Your Text ? ', (answer) => { // TODO: Log the answer in a database // console.log('Your name is:', answer); sock.write('Server :"' + answer + '"'); rl.close(); }); }); // 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'); const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Your Text : ', (answer) => { // TODO: Log the answer in a database // console.log('Your name is:', answer); client.write(answer); rl.close(); }); }); // 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(); const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Your Text : ', (answer) => { // TODO: Log the answer in a database // console.log('Your name is:', answer); client.write(answer); rl.close(); }); }); // Add a 'close' event handler for the client socket client.on('close', function() { console.log('Connection closed'); });
۹۵/۰۳/۲۶