http://www.2cto.com/kf/201403/285640.html
server.js
1 var io = require('socket.io').listen(8080); 2 io.set('log level', 1); 3 var users = {}; 4 io.sockets.on('connection', function (socket) { 5 io.sockets.emit('connect',{hell:'boy'}); 6 7 socket.on('private message', function (from,to,msg) { 8 console.log('I received a private message by ', from, ' say to ',to, msg); 9 if(to in users){ 10 users[to].emit('to'+to,{mess:msg}); 11 } 12 }); 13 socket.on('new user',function(data){ 14 if(data in users){ 15 16 }else{ 17 var nickname = data; 18 users[nickname]= socket; 19 } 20 console.info(users); 21 }); 22 socket.on('disconnect', function () { 23 io.sockets.emit('user disconnected'); 24 }); 25 });
测试页面index.html
1 <meta charset="utf-8"> 2 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 3 <script src="http://localhost:8080/socket.io/socket.io.js"></script> 4 <script> 5 $(function(){ 6 var socket = io.connect('http://localhost:8080'); 7 socket.on('connect', function (data) { 8 console.log(data); 9 }); 10 $("#send").click(function(e){ 11 var from = $('#user_name').val(), 12 msg = $('#message').val(), 13 to = $('#to').val(), 14 $message_list = $('#message_list'); 15 socket.emit('new user',from); 16 socket.emit('private message',from,to,msg); 17 socket.on('to'+from, function (data) { 18 $message_list.append('<li>'+data.from+'说'+data.message+'</li><li>'); 19 }); 20 }); 21 }); 22 </script> 23 24 25 姓名:<input id="user_name" type="text"><br> 26 发送给:<input type="text" id="to"><br> 27 消息内容:<input type="text" id="message"><button type="button" id="send">发送</button> 28 <ul id="message_list"> 29 30 </ul> 31 32 33 </li>