node io.sockt 聊天应用
index.html
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="output"></div> <script src="./socket.io/socket.io.js"></script> <script> var socket=io.connect('http://localhost:8080'); socket.on('connect',function(){ socket.emit('addme',prompt("Who are you?")); }) socket.on('chat',function(username,data){ var p=document.createElement("p"); p.innerHTML=username+ " : "+data; document.getElementById("output").appendChild(p); }) window.addEventListener('load',function(){ document.getElementById('sendtext').addEventListener('click',function(){ var text=document.getElementById("data").value; socket.emit('sendchat',text); },false); },false); </script> <div id="output"></div> <div id="send"><input type="text" id="data" size="100"><br><input type="button" id="sendtext" value="Send Text"></div> </body> </html>
app.js
var app=require('http').createServer(handler), io=require('socket.io').listen(app), fs=require('fs'); app.listen(8080); function handler(req,res){ fs.readFile(__dirname+'/index.html',function(err,data){ if (err) { res.writeHead(500); return res.end('Error loading chat.html'); } res.writeHead(200); res.end(data); }); } io.sockets.on("connection",function(socket){ socket.on('addme',function(username){ socket.username=username; socket.emit('chat','SERVER','You have connected'); socket.broadcast.emit('chat','SERVER',username+' is on deck'); }) socket.on('sendchat',function(data){ io.sockets.emit('chat',socket.username,data); }) socket.on('disconnect',function(){ io.sockets.emit('chat','SERVER',socket.username+' has left the building'); }) })
posted on 2013-10-17 15:07 Ijavascript 阅读(304) 评论(0) 编辑 收藏 举报