这里介绍使用一款简单易用的socket封装库socket.io.slim.js
.
下面是socket.io
一个聊天简单demo,大家可以下载尝试一下。
git clone https://github.com/socketio/chat-example.git
另外还有一篇不错的博文:https://www.cnblogs.com/renhui/p/6544835.html
这里我稍微加了几个自己的测试事件,
- client
<script>
//var host = 'http://localhost/'
//var socket = io(host, { forceNew: true }); //socket,
var socket = io();
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
console.log("aaa");
if (input.value) {
socket.emit('armwind', input.value);
input.value = '';
}
});
socket.on('connect', (msg) => {
console.log(msg);
console.log("client start connect server");
});
socket.on('connecting', () => {
console.log("connecting");
});
socket.on('disconnect', () => {
console.log("disconnect");
});
socket.on('armwind_test', (msg) => {
console.log("armwind_test msg");
console.log(msg);
});
socket.on('connect_timeout', (msg) => {
console.log("connect timeout");
});
socket.on('armwind', function(msg) {
console.log("bbb");
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
1.socket.on:用于设置事件的回调后函数,除了一些标准的消息外,其它消息可自己定义
2.socket.emit:发送某一消息。
- server
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
//设置clinet连接回调
io.on('connection', (socket) => {
console.log("connection");
socket.on('armwind', msg => {
console.log("start send");
io.emit('armwind', msg+"armwind");
io.emit('armwind_test', msg+"armwind_test"); //这里自定义了一个方法,可与服务端对应看
});
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
运行结果;