簡體   English   中英

為什么我的 socketio 沒有與我的 socketio-client 連接?

[英]Why my socketio is not connecting with my socketio-client?

我正在開發一個需要實時聊天的chatapp項目,所以我在服務器端使用了socketio,它是用nodejs編寫的,而不是在我的主要chatapp react-native項目中使用了socketio-client。

但是現在問題來了,我的套接字沒有初始化。 我無法將我的服務器與我的主應用程序連接起來。 我正在使用 socketio 和 socketio 客戶端,我的兩個套接字版本都是相同的 4.5.1,但它甚至沒有連接。 我曾嘗試使用舊版本的套接字,但它也無法正常工作,我還嘗試將我的本地主機端口更改為 4000,但它也無法正常工作。

我的服務器代碼:

const express = require('express');
var bodyParser = require('body-parser');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const port = process.env.PORT || 3000;

require('./src/config/database')
const user_routes = require('./src/user/users.routes');


app.use(bodyParser.urlencoded({extended: true}))
app.use(express.json())

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.use('/User', user_routes)
io.on('connection', (socket) => {
  console.log('a user connected');


  socket.on('send_message',(data)=>{
    console.log("received message in server side",data)
    io.emit('received_message',data)
  })

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
  
});

server.listen(port, () => {
  console.log( `Server running at http://localhost:${port}/`);
});

我的應用程序套接字服務文件代碼:

import io from 'socket.io-client';

const SOCKET_URL = 'http://localhost:3000'

class WSService {

    initializeSocket = async () => {
        try {

            this.socket = io(SOCKET_URL, {
                transports: ['websocket']
            })
            console.log("initializing socket", this.socket)

            this.socket.on('connect', (data) => {
                console.log("=== socket connected ====")
            })

            this.socket.on('disconnect', (data) => {
                console.log("=== socket disconnected ====")
            })

            this.socket.on('error', (data) => {
                console.log("socekt error", data)
            })

        } catch (error) {
            console.log("scoket is not inialized", error)
        }
    }

    emit(event, data = {}) {
        this.socket.emit(event, data)
    }
    
    on(event, cb) {
        this.socket.on(event, cb)
    }

    removeListener(listenerName) {
        this.socket.removeListener(listenerName)
    }

}

const socketServcies = new WSService()

export default socketServcies

在我標記它的地方應該連接 = true 但在開發控制台中它是錯誤的我已經完成了控制台日志所以檢查它是否正在連接,我可以看到它沒有連接。 如何使其連接?

我多次檢查過我的應用程序或服務器沒有錯誤,並且在我運行我的應用程序時我的服務器也在運行。

Answering my own question The problem was i was using android emulator and android in an emulator can't connect to localhost you need to use the proxy ip so when i add http://10.0.2.2:3000 in const SOCKET_URL = 'http://10.0.2.2:3000'比它的工作良好信用歸功於 gorbypark,他在 discord 中告訴我這個

我假設您的正面和背面都在本地主機中運行。 文檔說,如果前端與后端在同一個域中,則不需要使用 URL。 由於您聲明了options參數,因此您可以首先使用默認參數window.location

class WSService {

    initializeSocket = async () => {
        try {

            this.socket = io(window.location, {
                transports: ['websocket']
            })
            console.log("initializing socket", this.socket)

            this.socket.on('connect', (data) => {
                console.log("=== socket connected ====")
            })

            this.socket.on('disconnect', (data) => {
                console.log("=== socket disconnected ====")
            })

            this.socket.on('error', (data) => {
                console.log("socekt error", data)
            })

        } catch (error) {
            console.log("scoket is not inialized", error)
        }
    }

    emit(event, data = {}) {
        this.socket.emit(event, data)
    }
    
    on(event, cb) {
        this.socket.on(event, cb)
    }

    removeListener(listenerName) {
        this.socket.removeListener(listenerName)
    }

}

不要指定 socket-io 連接的主機/端口。 它可以自己弄清楚。

根據文檔,如果沒有將 URL 指定為參數,它會嘗試連接到window.location

所以而不是

            this.socket = io(SOCKET_URL, {
                transports: ['websocket']
            })

做就是了

            this.socket = io()

我不確定它是否適用於其他 arguments。 你可以試試這樣

            this.socket = io(undefined, {
                transports: ['websocket']
            })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM