参考资料
https://socket.io/get-started/chat/
https://www.imooc.com/learn/861
下载依赖包
npm install --save express@4.15.2
npm install --save socket.io
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</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>
<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(e){
console.log('asdsa ' + $('#m').val())
e.preventDefault();
// 发送信息
socket.emit('message', $('#m').val());
// $('#messages').append($('<li>').text($('#m').val()));
$('#m').val('');
return false;
});
socket.on('message', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('enter', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('leave', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
后端代码
// https://socket.io/get-started/chat/ 参考资料
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var userNum = 0
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
userNum++
socket.nickname = 'user' + userNum
io.emit('enter', socket.nickname + ' 进入')
socket.on('message', function(msg){
console.log('message: ' + msg);
io.emit('message', socket.nickname + ' say: ' + msg);
});
socket.on('disconnect', function(){
io.emit('leave', socket.nickname + ' left ');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
node server.js 启动即可