socket.io的基础教程
一、安装nodejs [默认安装][下载nodejs]
新建文件夹[socket],在目录下执行以下代码
nodejs中用npm初始化来创建package.json
npm init
二、使用npm下载 web框架express模块
npm install --save express@4.15.2
三、使用npm下载socket.io模块
npm install --save socket.io
四、新建index.js 代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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){ socket.on('bsh', function(msg){ io.emit('bsh', msg); }); });
http.listen(3000, function(){ console.log('listening on *:3000'); });
|
五、新建index.html 代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| <!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> <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('bsh', $('#m').val()); $('#m').val(''); return false; }); socket.on('bsh', function(msg){ $('#messages').append($('<li>').text(msg)); }); }); </script> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> </body> </html>
|
六、执行 node index.js
七、浏览器打开localhost:3000