【发布时间】:2021-12-16 12:03:29
【问题描述】:
在下面的代码中:
客户端应该开始向服务器发送很长的 Base64 字符串的图像,一个接一个地间隔很近。
一旦第一个带有 Base64 字符串的emit 发生,套接字就会断开连接。我尝试使用硬编码的 2 个字符的字符串,但没有发生这种情况。
我认为问题在于数据的大小,或者当第二个和第三个等..发出时套接字还没有完成第一个 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)
}
我做错了什么?
【问题讨论】:
-
您在问客户为什么要这样做,但您没有展示或描述有关客户的任何信息。这可能就是问题所在。
-
这里有个问题。你创建
httpServer。 http 服务器对象。然后将 socket.io 和 Express 连接到该 http 服务器。然后,您使用httpServer.listen(SOCKET_PORT)启动该服务器。没关系。然后,您调用app.listen(EXPRESS_PORT)启动另一台服务器。这很可能是不对的。您有两个独立的服务器,它们都将您的 Express 代码连接到它们。而且,其中一台服务器上有 socket.io。通常,您将拥有一个 Express 和 socket.io 都使用的 http 服务器。 -
SOCKET_PORT和EXPRESS_PORT的值是多少? -
我已经用客户端代码和 PORTS 的值更新了 OP
-
我使用 2 个不同的端口,因为当我为两个端口使用相同的端口时,它不起作用。我的 httpServer/app/socket 设置是从教程中复制/粘贴的,我不知道它是否正确,但它似乎可以工作.. 有点..
标签: node.js express server socket.io