![](/img/trans.png)
[英]How do I start websocket server (socketIO or otherwise) in Nuxt 3? Does not work the same as in Nuxt 2
[英]How do I fix socketio spamming polling when I start my web app? [javascript, expressjs, socketio]
這是問題所在。 當我在瀏覽器中加載頁面並檢查我的“測試”是否已發出時,我遇到了這堵垃圾郵件投票牆。
我使用的代碼與我完成的其他項目中的代碼完全相同,所以我認為這現在不起作用是沒有意義的。 -_-
應用程序.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8000;
server.listen(port, function(){
console.log('server ready - listening on *:8000');
});
app.get( '/*' , function( req, res, next ) {
//This is the current file they have requested
var file = req.params[0];
//Send the requesting client the file.
res.sendFile( __dirname + '/' + file );
});
io.on('connection', function (socket) {
socket.on('test', function(){
console.log("test worked");
});
});
客戶端.js
var socket = io();
socket.emit("test");
我將代碼分解為您在上面看到的內容。 沒有別的了。 它不起作用。 內心的尖叫
我會發布我的評論作為答案,以便您可以結束這個問題。 socket.io 會循環使用 http 請求並且永遠不會成功連接的一個常見原因是您在客戶端和服務器上運行的版本不匹配。 這似乎最近在 socket.io 上發生了最近的版本更改,因此他們必須對連接邏輯的工作方式進行了一些更改,如果版本不匹配,則無法連接。
如果您通過以下方式加載您的客戶端:
<script src="/socket.io/socket.io.js"></script>
然后,只要您沒有任何其他<script>
標記加載其他版本的 socket.io,客戶端將始終匹配服務器版本。
另一種對我有用的解決方案( Socket.IO 2.3.0 和 Socket.IO Client 2.3.0 )是在后端創建io
實例並在前端創建socket
時設置transports
字段,如下所示:
在后端:
io = require('socket.io')(http,{
log: false,
agent: false,
origins : '*:*' , // this is for the CORS browser error , I also use the cors npm module here
transports : [ 'websocket' ]
});
在前端:
const socket = socketIOClient(url,{
forceNew : false ,
secure : true ,
transports: [ 'websocket' ]
});
希望它有所幫助,如果不是問題所有者,那么也許是其他人:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.