設置一個簡單的HTML網頁,提供一個表單和一個信息的列表,經過node.js進行框架的搭建html
使用node.js框架node
1.新建一個chat-example文件夾,並創建一個package.json文件jquery
{ "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "dependencies": {} }
2. 經過npm安裝express,並創建index.js文件配置信息express
npm install --save express@4.15.2
var app = require('express')(); var http = require('http').Server(app); app.get('/', function(req, res){ res.send('<h1>Hello world</h1>'); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
3.在命令行運行node index.js 你能夠獲得npm
在瀏覽器運行http://localhost:3000你能夠獲得json
4.HTML頁面的創建瀏覽器
建立index.html,並修改index.js裏面的app.get函數,將路由鏈接到index.Htmlapp
<!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> </body> </html>
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
5.整合socket.Io框架
先安裝socket.iosocket
npm install --save socket.io
通常安裝完,package.json會自動更新,再編輯index.js文件
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
給index.html裏面增長js代碼,調取socket和jq框架,進行html和http的鏈接。
<script src="/socket.io/socket.io.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> $(function () { var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); }); </script>
Index.js修改獲取chat message節點,經過控制檯查看message
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
經過io.emit進行事件發送
io.emit('some event', { for: 'everyone' });
簡單起見,咱們將發送消息給每一個人,包括髮送方。
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
<script> $(function () { var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); }); </script>