hello guys, pada post kali ini saya akan memnbahas tentang Node.JS dan membuat aplikasi chatting menggunakan platform ini :)
Node.js adalah sebuah platform dibangun di Chrome Javascript runtime easily building fast, scalable network applications. Node.js menggunakan model event-driven, non-blocking I/O yang membuatnya ringan dan efisien, cocok untuk real-time aplikasi yang berjalan di perangkat yang didistribusikan. Javascript adalah bahasa berbasis event-driven, dan Node.js menggunakan ini untuk keuntungan menghasilkan server yang scalable. Menggunakan arsitektur yang disebut event-loop. Nah berikut sedikit video persentasi Ryan Dahl :
Nah langsung aja kita mulai. Pertama -tama tentu saja silahkan download Node.JS di sini http://nodejs.org.. Sebelum mulai kita butuh node package manager(npm) yaitu Socket.IO. Apa itu Socket.IO ? berikut penjelasan singkatnya :
"Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. It's care-free realtime 100% in JavaScript." sumber : http://socket.io
Nah sekarang langsung saja install Node.JS dan run, lalu tulis perintah ini : npm install socket.io
var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') var usernames={}; app.listen(9999); function handler (req, res) { //console.log(req); fs.readFile(__dirname + '/index4.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } io.sockets.on('connection', function(socket){ console.log("Connection " + socket.id + " accepted."); console.log(socket.handshake.foo == true); // writes `true` console.log(socket.handshake.address.address); // writes 127.0.0.1 socket.on('adduser', function(username){ // store the username in the socket session for this client socket.username = username; // add the client's username to the global list usernames[username] = socket.id; // send client to room 1 console.log(username+' has connected to the server'); socket.broadcast.emit('updatechat', ' has connected',username); }); // now that we have our connected 'socket' object, we can // define its event handlers socket.on('message', function(message){ // we tell the client to execute 'updatechat' with 2 parameters io.sockets.emit('updatechat', message,socket.id); console.log("Received message: " + message + " - from client " + socket.username); }); socket.on('pmessage',function(message){ // This works and sends message to all clients //io.sockets.emit("updatechat",message,socket.username); console.log(usernames[message] + " " + socket.id + " to " + message); // THIS DOESNOT io.sockets.socket(usernames[message]).emit("updatechat","Ping" + message,socket.username); }); socket.on('disconnect', function(){ io.sockets.emit('usersleft', socket.username); delete usernames[socket.username]; //socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected'); console.log("Connection " + socket.id + " terminated."); }); });Selanjutnya kita buat untuk script di sisi client-nya :
<!doctype html> <html> <head> <title>Socket.io Test</title> <script src="/json.js"></script> <!-- for ie --> <script src="/socket.io/socket.io.js"></script> </head> <body> <script> var firstconnect = true; var socket; function connect() { if(firstconnect) { socket = io.connect(null); socket.on('message', function(data){ message(data); }); socket.on('connect', function(){ socket.emit('adduser', prompt("What's your name?")); status_update("Connected to Server"); }); socket.on('disconnect', function(){ status_update("Disconnected from Server"); }); socket.on('reconnect', function(){ status_update("Reconnected to Server"); }); socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in " + nextRetry + " seconds"); }); socket.on('reconnect_failed', function(){ message("Reconnect Failed"); }); socket.on('updatechat', function (message,socketid) { document.getElementById('rec').innerHTML += "Socketid :" + socketid+" Broadcast says: " + message + " <br>"; //$('#conversation').append('<b>'+username + ':</b> ' + data + '<br>'); }); socket.on('usersleft', function (socketid) { document.getElementById('rec').innerHTML += "<b>Socketid :" + socketid+" has been left</b><br>"; }); firstconnect = false; } else { socket.socket.reconnect(); } } function disconnect() { socket.disconnect(); } function message(data) { document.getElementById('message').innerHTML = "Server says: " + data; } function status_update(txt){ document.getElementById('status').innerHTML = txt; } function esc(msg){ return msg.replace(/</g, '<').replace(/>/g, '>'); } function send() { socket.emit('message',document.getElementById('andy').value); }; function pingID(id) { socket.emit('pmessage',document.getElementById('andy2').value); } </script> <h1>Socket.io Test</h1> <div><p id="status">Not Connected</p></div> <div><p id="message"></p></div> <button id="connect" onClick='connect()'/>Connect</button> <button id="disconnect" onClick='disconnect()'>Disconnect</button> <input type="text" id="andy" /> <button id="send" onClick='send()'/>Send Message</button> <input type="text" id="andy2" /> <button id="send" onClick='pingID()'/>pingID Message</button> </hr> <div><p id="rec"></p></div> </body> </html>Untuk langkah terakhir mari kita jalankan script yang di atas. Silahkan ketika node <nama_file_server>
Dan simple aplikasi chatting sudah jadi :
Sumber :
http://psitsmike.com/2011/09/node-js-and-socket-io-chat-tutorial/
Node: Up and Running
No comments:
Post a Comment