socket.io 由于数据大小而断开连接
socket.io disconnects due to the size of data
在下面的代码中:
客户端应该开始向服务器发送长 Base64 字符串的图像,一个接一个地间隔很近。
一旦第一个带有 Base64 字符串的 emit
发生,套接字就会断开连接。我尝试使用硬编码的 2 个字符的字符串,但没有发生这种情况。
我认为要么是数据的大小有问题,要么是当第二个和第三个等发出时,socket 还没有完成第一个 Base64 字符串的发出。
const io = new Server(httpServer, {
cors: {
credentials: true,
origin: 'http://localhost:4200',
methods: ["GET", "POST"]
}
})
io.on('connection', function(socket) {
console.log('connected')
socket.on('newDataFromClient', async (newDataFromTheClient) => {
// will work only after I refresh the page after a login
})
socket.on('disconnect', (reason) => {
// the reason is "transport error"
console.log('disconnected due to = ', reason)
})
})
httpServer.listen(4200)
这是客户端代码:
let socket
// this is only executed once, on page load
function setup() {
fetch('/setup')
.then((response) => response.json())
.then((setup) => {
doSomething(setup)
socket = io('http://localhost:4200', {
withCredentials: true,
transports: ['websocket']
})
})
}
// this is executed repeatedly at close intervals
async function sendToServer(imageAsBase64) {
socket.emit('newDataFromClient', imageAsBase64)
}
我做错了什么?
问题是 socket.io 的 maxHttpBufferSize
限制,set to 1Mb by default。
我发送的每个 Base64 字符串大约为 2.5Mb。
我必须将我的服务器端代码更新为
const io = new Server(httpServer, {
cors: {
origin: 'http://localhost:4200',
methods: ["GET", "POST"]
},
maxHttpBufferSize: 4e6 // 4Mb
})
现在一切正常。我找到了 answer here.
在下面的代码中:
客户端应该开始向服务器发送长 Base64 字符串的图像,一个接一个地间隔很近。
一旦第一个带有 Base64 字符串的 emit
发生,套接字就会断开连接。我尝试使用硬编码的 2 个字符的字符串,但没有发生这种情况。
我认为要么是数据的大小有问题,要么是当第二个和第三个等发出时,socket 还没有完成第一个 Base64 字符串的发出。
const io = new Server(httpServer, {
cors: {
credentials: true,
origin: 'http://localhost:4200',
methods: ["GET", "POST"]
}
})
io.on('connection', function(socket) {
console.log('connected')
socket.on('newDataFromClient', async (newDataFromTheClient) => {
// will work only after I refresh the page after a login
})
socket.on('disconnect', (reason) => {
// the reason is "transport error"
console.log('disconnected due to = ', reason)
})
})
httpServer.listen(4200)
这是客户端代码:
let socket
// this is only executed once, on page load
function setup() {
fetch('/setup')
.then((response) => response.json())
.then((setup) => {
doSomething(setup)
socket = io('http://localhost:4200', {
withCredentials: true,
transports: ['websocket']
})
})
}
// this is executed repeatedly at close intervals
async function sendToServer(imageAsBase64) {
socket.emit('newDataFromClient', imageAsBase64)
}
我做错了什么?
问题是 socket.io 的 maxHttpBufferSize
限制,set to 1Mb by default。
我发送的每个 Base64 字符串大约为 2.5Mb。
我必须将我的服务器端代码更新为
const io = new Server(httpServer, {
cors: {
origin: 'http://localhost:4200',
methods: ["GET", "POST"]
},
maxHttpBufferSize: 4e6 // 4Mb
})
现在一切正常。我找到了 answer here.