Skip to main content
Version: 4.x

教程步骤 #4 - 触发事件


触发事件

Socket.IO 背后的主要思想是你可以发送和接收任何你想要的事件以及任何你想要的数据。 任何可以编码为 JSON 的对象都可以,并且也支持 二进制数据

英:The main idea behind Socket.IO is that you can send and receive any events you want, with any data you want. Any objects that can be encoded as JSON will do, and binary data is supported too.

让我们这样做,以便当用户输入消息时,服务器将其作为 chat message 事件获取。 index.html 中的 script 部分现在应如下所示:

英:Let’s make it so that when the user types in a message, the server gets it as a chat message event. The script section in index.html should now look as follows:

<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();

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

form.addEventListener('submit', (e) => {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
</script>

index.js 中,我们打印出 chat message 事件:

英:And in index.js we print out the chat message event:

io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});

结果应如以下视频所示:

英:The result should be like the following video:

https://i.cloudup.com/transcoded/zboNrGSsai.mp4

info

你可以直接在浏览器中运行此示例:

英:You can run this example directly in your browser on: