官网网站:https://socket.io/docs/#Installing
强调:socket io的版本不一样,代码的实现也不一样,如果直接用命令获取的是最新版本,在百度查询代码的实现码时,运行可能会直接报错,或者不断的加载的问题。建议参照官网的最新写法较为妥当
命令:
npm install --save socket.io
已下是2种版本的写法:
1."socket.io": "^2.2.0"
service.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3015);
// WARNING: app.listen(80) will NOT work here!
app.get('/', function (req, res) {
res.sendFile(__dirname + '/page/index.html');
});
io.on('connection', function (socket) {
socket.on('my other event', function (data) {
console.log(data);
//获取自己的聊天信息
socket.emit('news', data);
//获取其他人聊天信息
socket.broadcast.emit('news', data);
});
});
index.html
//此处js的引用是nodejs已经封装过的,可以应用到
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3015');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
2."socket.io": "^1.7.3"
service.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3015;
app.get('/', function(req, res){
res.sendFile(__dirname + '/page/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function () {
// logger.info('SocketIO : Received ' + nb + ' messages');
// logger.info('SocketIO > Disconnected socket ' + socket.id);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
index.html
<!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; }
#messages { margin-bottom: 40px }
</style>
</head>
<body>
11
<ul id="messages"></ul>
<form >
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io('http://localhost:3015');
// 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));
window.scrollTo(0, document.body.scrollHeight);
});
});
</script>
</body>
</html>