Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

node.js - Setup socket io in react and node

Try to implement socket to my react and node app. can someone please tell me, what am I doing wrong. in Node, the only way that that i can get access to io.on is with the new Server(http). in Client, socket object does console log but the property connected is false.

--I have no connection to socket, nothing is happening ("user connected" is not console.log in node)

Node

require("./config/mysql");
require("dotenv").config();
const express = require("express");
const http = require("http");
const cors = require("cors");

const app = express();
const server = http.createServer(app);
// const io = require("socket.io")(server);

const { Server } = require("socket.io");
const io = new Server(http);

io.on("connection", (socket) => {
 console.log(socket);
  console.log("user connected");

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

app.use(express.json());
app.use(cors());

const PORT = process.env.PORT || 5001;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

React

import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import "./Chat.css";
import ChatSingleMessage from "../../components/ChatSingleMessage/ChatSingleMessage";
import { io } from "socket.io-client";

const ENDPOINT = "http://localhost:5000/";
const socket = io(ENDPOINT);

const Chat = () => {


 useEffect(() => {
   socket.on("connect", () => {
   console.log("connect");
   });

     console.log(socket);


 }, []);

    return ( JSX Stuff );
 };
 export default Chat;
question from:https://stackoverflow.com/questions/65880871/setup-socket-io-in-react-and-node

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

just need to use version 2.3.0 instead


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...