Socket.IO使用
一、server
1-1、依赖引入
npm install socket.io
1-2、注册
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.send({
data: 'hello world!'
})
});
io.on('connect', client => {
console.log("连接成功");
client.emit("message", "你好啊!赛利亚");
})
io.on("connection", client => {
client.emit("message", "你好!");
client.on("eventname", msg => {
console.log("接收到来自客户端的eventname事件", msg);
});
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
二、client
2-1、依赖引入
npm install socket.io-client
import { io } from "socket.io-client";
//或者 import io from "socket.io-client";
//const socket = io(path, options)
const socket = io('http://127.0.0.1:3000',#'ws://127.0.0.1:3000'
{
path: '',# socket.io 库默认服务端path为/socket.io
transports:['websocket','xhr-polling','jsonp-polling'] #此配置在我的代码中表现为必须项,官方示例未列出,请指教
})
socket.on("connect", (res) => {
console.log("#connect: ", res);
});
socket.on("message", (res) => {
console.log("#message: ", res);
});
socket.on('disconnect', () => {
console.log('断开连接')
})
疑惑之处
在添加transports选项之前,一直捣鼓了很久都找不到原因,直到查了很多文章,发现有些人会有这个选项,就试一试,发现居然通了.....;其它大部分文章没有添加这一选项。请有研究的同学知道的话为我解答一下。