nodejs之聊天室
服务器端代码
var http = require('http'), io = require('socket.io'), fs = require('fs'); //配置 var config = { port : 8888 } http = http.createServer(handler); http.listen(config.port); io = io.listen(http); function handler(req, res) { if(req.method=="GET"){ }else if(req.method=="POST"){ console.info(); } fs.readFile(__dirname+'/client.html',function(err,data){ if(err){ throw err;}else{ res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'}); res.write(data.toString()); res.end(); } }); } //'connection' 是socket.io 保留的 io.sockets.on('connection',function(socket){ //'msg'是我们自定义的,客户端听取的时候要指定同样的事件名 socket.emit('msg',{hi:'欢迎来到聊天室'}); //'msg'需要和客户端发送时定义的事件名相同 socket.on('msg',function(data){ console.log('Get a msg from client ...'); console.log(data); socket.broadcast.emit('user message',data); }); });
客户端代码
<!DOCTYPE html> <html> <head> <title> 聊天室 </title> <script src="/socket.io/socket.io.js"></script> <script type="text/javascript"> var socket = io.connect('http://localhost:8888'); socket.on('user message',function(msg){ //alert(msg); msgbox(msg.msg,msg.user); }); function sendMsg(){ var inpt = document.getElementById('txtInput'); var yhm = document.getElementById('yhm'); var str = inpt.value; msgbox(str,yhm.value); //发送 socket.emit('msg',{msg:str,user:yhm.value}); console.log('[client]' + str); inpt.value = ""; inpt.focus(); } function msgbox(str,user){ //alert(user) var box = document.getElementById('box'); box.innerHTML += '<b>'+user+'</b>:'+str + '<br/>'; } </script> <style type="text/css"> #box { overflow: auto; width:500px;height:300px;border:1px solid #dcdcdc; } #txtInput { width:430px; } </style> </head> <body> <label>用户名</label><input type="text" id="yhm"> <h2>聊天室</h2> <div id='box' ></div> <input type='text' id='txtInput' ><input type='button' value='发送' onclick='sendMsg();'> </body> </html> demo
效果预览

第一次写博客,写的不是很好,希望大家多多体谅,有什么问题可以给我留言
JAVA js JQurey EasyUI nodejs 等随笔

浙公网安备 33010602011771号