WebSocket 从入门到实战开发

socket 官网的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();

var form = document.getElementById('form');
var input = document.getElementById('input');

form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
// 发送消息
socket.emit('chat message', input.value);
input.value = '';
}
});
// 接受消息
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
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
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);

app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
// 接受消息
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
// 广播 服务器端发送消息
socket.broadcast.emit('hi');
socket.emit('hi');

// 一对一
socket.to(id).emit('chat message', input.value);

// 断开连接
socket.on('disconnecting',function(){
});
});

http.listen(3000, () => {
console.log('listening on *:3000');
});

客户端

socket.io-client


相关资料
手摸手教你使用WebSocket
你不知道的WebSocket
零距离接触websocket
socketio

5000字!带你零距离接触websocket!

作者

Fallen-down

发布于

2020-06-02

更新于

2021-03-16

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.
You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.