簡體   English   中英

將socket.io與React一起使用

[英]Use socket.io with React

如何在React中使用socket.io? 我的客戶有以下代碼:

import React, { Component } from "react"
import io from "socket.io-client"
import "./App.css"

const socket = io()
console.log(socket)

class App extends Component {
    render() {
        return (
            // ...
        )
    }
}

export default App

對於我的服務器:

const express = require("express"),
    app = express(),
    http = require("http").Server(app),
    io = require("socket.io")(http)

io.on("connection", socket => {
    console.log("New connection")
})

http.listen(8000, () => {
    console.log("Started!")
})

但我不斷收到此錯誤:

POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MdZyD8L 404 (Not Found)

我做錯了什么? 謝謝。

PS:要啟動該應用程序,我要執行npm run start ,並且對於服務器node server/server.js

還沒有真正運行過代碼; 但是,您是否注意到錯誤中的端口是3000,而不是初始化服務器以偵聽的8000

閱讀https://socket.io/docs/client-api/ ,它說默認值是窗口位置,知道有反應,您可能在端口3000上運行,該端口與錯誤中的端口3000相同

初始化套接字對象時嘗試設置端口

const socket = io("localhost:8000");

下面是用於通過套接字連接的代碼,如果您希望在頁面渲染后再通過套接字進行連接,然后將其寫入componentDidMount中。

import React, { Component } from "react"
import io from "socket.io-client"
import "./App.css";

class App extends Component {

componentDidMount(){
let socket = io.connect("http://localhost:8000");
   console.log(socket)
}
    render() {
        return (
            // ...
        )
    }
}

export default App

例如,您可以通過以下鏈接進行鏈接: https : //medium.freecodecamp.org/how-to-create-a-realtime-app-using-socket-io-react-node-mongodb-a10c4a1ab676

暫無
暫無

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

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