SocketIO客户端和NodeJS-连接正常,但发射/发光不起作用

时间:2020-06-12 06:36:18

标签: node.js

我获得了成功的“用户出现了!”后端上的连接消息。 connect事件之后似乎没有任何通信。

此外,前端不断断开连接并重新连接。这不好吗?

这里的超级套接字新手,今晚才开始学习。

预先感谢您的帮助。

Node.JS / Express后端:

const express = require('express')
const server = express();
const http = require('http').createServer(server);
const socketio = require('socket.io');

// ! Express --

server.use(require('cors')());
server.use(express.json());

server.get("/", (req, res) => {
    res.status(200).json({
        message: `You've hit the socket.io backend!`
    })
})

// ! SocketIO
const io = socketio(http);
io.on('connect', socket => {
    // ! Emit CheatSheet -> https://socket.io/docs/emit-cheatsheet/
    // -> I believe `socket` referes to the open instance of a connection.
    // -> This allows us to use functions such as:
    // -> .on(eventName, cb(data)) | Use `on` when you are getting data FROM the front end.
    // -> .emit(eventName, { data }) | Use `emit` when you are sending data TO the front end.
    console.log(`A user has appeared!`)

    socket.on("hello", data => console.log(data))

    socket.on('disconnect', () => {
        console.log(`A user has disappeared.`)
    })
});

const PORT = process.env.PORT || 5000;
http.listen(PORT, () => console.log(`Server started on ${PORT}.`));

反应前端(App.js):

import React, { useEffect, useState } from 'react'

// -> SocketIO
import io from 'socket.io-client';
let socket;

export default () => {
  const ENDPOINT = process.env.ENDPOINT || 'http://--server-ip--/'
  const [message, setMessage] = useState('Secret Message from the Front-End')

  useEffect(() => {
    socket = io(ENDPOINT, {
      transports: ['websocket']
    });

    socket.emit('hello', "Hello from the front-end!")
  }, [ENDPOINT]);

  return (
    <div>
      <p>{ message }</p>
    </div>
  )
}

1 个答案:

答案 0 :(得分:0)

在客户端中,您必须等待使用适当的事件建立连接,然后发出某些东西

  useEffect(() => {
    socket = io(ENDPOINT, {
    transports: ['websocket']
   });
   socket.on('connect', function(){
         socket.emit('hello', "Hello from the front-end!")
   });

   }, [ENDPOINT]);