简体   繁体   English

如何在 socket.io-client 中建立连接并做出反应?

[英]How to establish connection in socket.io-client and react?

I have an issue with using socket.io-client with react.我在使用带有反应的 socket.io-client 时遇到问题。 Im just starting how to use it so i wanted to display a message in console when there is a connection but nothing appears in console.我刚刚开始如何使用它,所以我想在有连接时在控制台中显示一条消息,但控制台中没有出现任何内容。 Yes i have both react app and server running.是的,我同时运行了反应应用程序和服务器。

server.js服务器.js

const app = require('express')

const http = require('http').createServer(app)
const io = require('socket.io')(http)

let subject = ''

io.on('connection', (socket) => {
    console.log('ahoj')
    
})

http.listen(4001,function(){
    console.log('listening on port 4001')
})

App.js应用程序.js

import './App.css';
import CreateSubject from './components/CreateSubject'
import Hangman from './components/Hangman'
import { HangmanProvider } from './context/HangmanContext'
import io from 'socket.io-client'

io.connect('http://localhost:4001')



function App() {
  return (
    <HangmanProvider>
      <div className="App">
        <CreateSubject/>
        <Hangman/>
      </div>
    </HangmanProvider>
  );
}

export default App;

expected console.log预期的 console.log

listening on port 4001
ahoj

my console.log我的控制台.log

listening on port 4001

Add this to your server.js file to enable cors, here "3000" is the port where your React app is running.将此添加到您的 server.js 文件以启用 cors,此处“3000”是您的 React 应用程序运行的端口。

const io = require("socket.io")(http, {
  cors: {
     origin: "http://localhost:3000",
  },
});

To your App.js file add these lines在您的 App.js 文件中添加这些行

 import socketIOClient from 'socket.io-client';
 const ENDPOINT = 'http://localhost:4001';

 useEffect(() => {
   const socket = socketIOClient(ENDPOINT);
   socket.onAny((event, ...args) => {
    console.log(event, args);
   });
 }, []);
 

Replace: import { io } from 'socket.io-client';替换: import { io } from 'socket.io-client';

With: import socketIOClient from 'socket.io-client';与:从'socket.io-client'导入socketIOClient;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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