The server
dynamically generates socket.io in the root directory of the server running the client js file the client can add a reference through a fixed path /socket.io/socket.io.js
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
io.emit('user connect',user+'进入聊天室');
The emit function has two parameters
. The first parameter is a custom event name, what type of event name is sent by the sender, and the receiver can monitor the reception by the corresponding event name; the second parameter is the data to be sent
Server
var server = require('http').createServer(),
io = require('socket.io')(server);
server.listen(8000);
//因为 WebSocket 协议是建立在 HTTP 协议之上的,所以在创建 WebSocket 服务时需要调用 http 模块并调用其下的 createServer 方法,将生成的 server 作为参数传入 socket.io 的方法中。
io.onconnection(socket)
//io 的 connection 事件表示客户端与服务器成功建立连接,它会接收一个回调函数,该回调函数会接收一个 socket 参数。
io.on('connection', (socket) => {
io.emit('server message', {msg: 'Hello World.'})
//io.emit 方法用于向服务器发送消息,其第一个参数表示自定义的数据名,后面表示需要配合事件传入的参数。
});
socket.on(EventName, callback)
io.on('connection', (socket) => {
socket.on('client message', (data) => {
console.log(data);
});
});
socket.broadcast.emit()
//socket.on 方法用于接收客户端发送来的消息,EventName 参数为客户端自定义的事件名,callback 为回调函数,回调函数接收的参数即客户端传递来的参数。
io.on('connection', (socket) => {
socket.broadcast.emit('server message', {
msg: 'Hello World.'
});
});
socket.ondisconnect
//socket.broadcast.emit() 方法表示向除了自己以外的客户端发送消息。举个例子,当我们输入 “Message” 点击发送,只需要将 “Message” 通过服务器发送给其他客户端用于显示,而本地只需要将 “Message” 通过 js 代码添加进聊天窗口即可,而不需要经过服务器。
io.on('connection', (socket) => {
socket.on('disconnect', () => {
console.log('连接已断开...');
});
});
// disconnect 事件表示客户端与服务端断开连接。
Kefuduan
<html>
<head>
<title>Socket.IO chat</title>
<script src="/socket.io/socket.io.js"></script>
//引入 socket.io 模块中的 socket.io.js 文件。
</head>
</html>
var socket = io();
socket.emit(EventName, param1, param2, …..)
//引入成功后,就可能通过 io() 生成客户端所用的 socket 对象。
//客户端
var socket = io();
socket.emit('client message', {
msg: 'Hello Server'
});
//服务端
io.on('connection', (socket) => {
socket.on('client message', (data) => {
console.log(data.msg); // Hello Server
});
});
socket.on(EventName)
//socket.emit 方法用于客户端向服务端发送消息,服务端用socket.on 方法来接收消息。