Node.js 和Socket.IO 实现chat
生活随笔
收集整理的這篇文章主要介紹了
Node.js 和Socket.IO 实现chat
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用 Node.js 和 Socket.IO 構建簡單的聊天程序
在node.js根目錄下創建文件夾chat,里面添加兩個文件:app.js和index.html
app.js
var fs = require('fs'), http = require('http'), socketio = require('socket.io');var server = http.createServer(function(req, res) {res.writeHead(200, { 'Content-type': 'text/html'});res.end(fs.readFileSync(__dirname + '/index.html')); }).listen(8080, function() {console.log('Listening at: http://localhost:8080'); });socketio.listen(server).on('connection', function (socket) {socket.on('message', function (msg) {console.log('Message Received: ', msg);socket.broadcast.emit('message', msg);}); });?
index.html
<html> <head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><script src="/socket.io/socket.io.js"></script><script>$(function(){var iosocket = io.connect();iosocket.on('connect', function () {$('#incomingChatMessages').append($('<li>Connected</li>'));iosocket.on('message', function(message) {$('#incomingChatMessages').append($('<li></li>').text(message));});iosocket.on('disconnect', function() {$('#incomingChatMessages').append('<li>Disconnected</li>');});});$('#outgoingChatMessage').keypress(function(event) {if(event.which == 13) {event.preventDefault();iosocket.send($('#outgoingChatMessage').val());$('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));$('#outgoingChatMessage').val('');}});});</script> </head> <body> Incoming Chat: <ul id="incomingChatMessages"></ul> <br /> <input type="text" id="outgoingChatMessage"> </body> </html>開啟服務器
node chat/app.js
打開兩個chrome輸入localhost:8080
這樣就看到效果了,然后你可以慢慢研究代碼了,再然后就洗洗睡吧。
?使用的源碼來自http://www.open-open.com/lib/view/open1337216216557.html
?
?
?
?
轉載于:https://www.cnblogs.com/wancy86/archive/2013/04/28/socket-io_chat.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Node.js 和Socket.IO 实现chat的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 随手写个pwd命令
- 下一篇: 删除系统Win7系统盘越来越小,系统盘清