简体   繁体   中英

Socket.io is not connecting Node.js server to React.js client

So what I am trying is to establish a socket.io connection between an express server and a react client. Maybe also mentionable the client is hosted on netlify and the server on heroku. The actual problem is the client seems to connect and receives the upgrade protocol to websocket messages with a HTTP 101. But nothing else happens afterwards. No "connection" or "connected" event is emitted. Maybe some one spots a mistake in the code or can guide me to the solution.

Server

/**
 *  App Configuration
 */
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server, {
  cors: {
    origin: process.env.CLIENT_URL,
    methods: ["GET", "POST"],
    credentials: true
  }
});

/**
 * Socket IO
 */
io.on("connection", (socket: any) => {
  console.log("Client Connected via Socket");
  
  // Join a conversation
  const { deviceId } = socket.handshake.query;
  socket.join(deviceId);

  // Leave the room if the user closes the socket
  socket.on("disconnect", () => {
    socket.leave(deviceId);
  });
});

/**
 * Server Activation
 */
app.listen(process.env.PORT, () => {
  console.log(`Listening on port ${process.env.PORT}`);
});

Client

  const socketRef = useRef();

  useEffect(() => {
    // Creates a WebSocket connection
    socketRef.current = io(process.env.REACT_APP_API, {
      transports: ['websocket'],
      query: { deviceId: 'test-id' }
    });

    socketRef.current.on('connect', () => {
      console.log("connected");
    });

    // Listens for incoming messages
    socketRef.current.on("message", (message) => {
      console.log(message);
    });
    
    // Destroys the socket reference
    // when the connection is closed
    return () => {
      socketRef.current.disconnect();
    };
  }, []);

Edit: Adding an image of the recurring http message about the websocket upgrade. HTTP Message

Change Server activation line to below

server.listen(process.env.PORT, () => {
  console.log(`Listening on port ${process.env.PORT}`);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM