一、服务器端:
1 var app = require('http').createServer(handler),
2 io = require('socket.io').listen(app),
3 fs = require('fs');
4
5 app.listen(999);
6
7 function handler(req, res) {
8 fs.readFile(__dirname+'/client.htm',
9 function(err, data){
10 res.writeHead(200);
11 res.end(data);
12 });
13 }
14
15 io.sockets.on('connection',function(socket){
16
17 socket.on('msg',function(data){
18 console.log('Get a msg from client');
19 console.log(data);
20 socket.broadcast.emit('usermsg',data);
21 });
22 });
二、客户端代码:
<html>
<head>
<title>Chat Room</title>
<script src="http://10.190.19.38:999/socket.io/socket.io.js"></script>
<script type="text/javascript">
var hotline = io.connect('http://10.190.19.38:999');
hotline.emit('msg','hi it is client!');
hotline.on('user message',function(data){
document.getElementById('chatbox').innerHTML += data+"<br>";
});
function sendToSer(){
text = document.getElementById('send-content').value;
hotline.emit('msg',text);
}
</script>
</head>
<body>
<h1>Chat Room</h1>
<input type='text' id= 'send-content'>
<input type='button' value='send' onclick='sendToSer()'>
<div id="chatbox"></div>
</body>
</html>
参考连接:http://www.cnblogs.com/hsxixi/archive/2011/12/25/2300883.html
注释待加。。。。。。。。。。。。。。。