Socket.IO 和 Node.js 聊天程序

来源:互联网 发布:nativeshare.js下载 编辑:程序博客网 时间:2024/05/10 12:30

1、安装 node.js

2、安装 socket.io

    npm install socket.io

3、创建文件app.js

[javascript] view plaincopy
  1. var fs = require('fs'),   
  2.       http = require('http'),  
  3.       socketio = require('socket.io');  
  4.   
  5. var server = http.createServer(function(req, res) {  
  6.     res.writeHead(200, { 'Content-type''text/html'});  
  7.     res.end(fs.readFileSync(__dirname + '/index.html'));  
  8. }).listen(8080, function() {  
  9.     console.log('Listening at: http://localhost:8080');  
  10. });  
  11.   
  12. socketio.listen(server).on('connection'function (socket) {  
  13.     socket.on('message'function (msg) {  
  14.         console.log('Message Received: ', msg);  
  15.         socket.broadcast.emit('message', msg);  
  16.     });  
  17. });  

3、创建文件index.html 下载socket.io并引入socket.io.js

[html] view plaincopy
  1. <html>  
  2. <head>  
  3.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>  
  4.     <script src="/socket.io/socket.io.js"></script>  
  5.     <script>  
  6.         $(function(){  
  7.             var iosocket = io.connect();  
  8.             iosocket.on('connect', function () {  
  9.                 $('#incomingChatMessages').append($('<li>Connected</li>'));  
  10.                 iosocket.on('message', function(message) {  
  11.                     $('#incomingChatMessages').append($('<li></li>').text(message));  
  12.                 });  
  13.                 iosocket.on('disconnect', function() {  
  14.                     $('#incomingChatMessages').append('<li>Disconnected</li>');  
  15.                 });  
  16.             });  
  17.             $('#outgoingChatMessage').keypress(function(event) {  
  18.                 if(event.which == 13) {  
  19.                     event.preventDefault();  
  20.                     iosocket.send($('#outgoingChatMessage').val());  
  21.                     $('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));  
  22.                     $('#outgoingChatMessage').val('');  
  23.                 }  
  24.             });  
  25.         });  
  26.     </script>  
  27. </head>  
  28. <body>  
  29. Incoming Chat: <ul id="incomingChatMessages"></ul>  
  30. <br />  
  31. <input type="text" id="outgoingChatMessage">  
  32. </body>  
  33. </html>  

4、然后运行 app.js 文件:

node app.js

5、打开两个浏览器,访问 http://localhost:8080/ 地址开始互聊了

0 0
原创粉丝点击