socket.io未连接到客户端

时间:2019-10-16 02:22:29

标签: javascript reactjs socket.io next.js

我正在尝试在next.js设置中通过socket.io向客户端发送数据。但是我没有通过它获取任何数据。

下面是我的server.js代码

    const app = require('express')()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const nextApp = next({ dev })
const nextHandler = nextApp.getRequestHandler()

// socket.io server
io.on('connection', socket => {
  console.log('a user is connected')
  socket.broadcast.emit('now', {
    message: 'Hello'
  })
  socket.on('disconnect', () => {
    console.log('user disconnected')
  })
})

nextApp.prepare().then(() => {

  app.get('*', (req, res) => {
    return nextHandler(req, res)
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

连接用户后,控制台会记录a user is connected的工作正常。

进入我的_app.js文件中,我已按照next.js示例中的说明包含了socket.io:https://github.com/zeit/next.js/blob/canary/examples/with-socket.io/pages/_app.js

这是我的_app.js文件

    import App from 'next/app'
import React from 'react'
import io from 'socket.io-client'

class MyApp extends App {
  static async getInitialProps ({ Component, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps }
  }
  state = {
    socket: null
  }
  componentDidMount () {
    // connect to WS server and listen event
    const socket = io()
    this.setState({ socket })
  }

  // close socket connection
  componentWillUnmount () {
    this.state.socket.close()
  }

  render () {
    const { Component, pageProps } = this.props
    return <Component {...pageProps} socket={this.state.socket} />
  }
}

export default MyApp

主要问题是在index.js文件中。下面是该文件

import { Component } from 'react'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

class ChatOne extends Component {
  // init state with the prefetched messages
  state = {
    message: ''
  }
  componentDidMount () {
    this.props.socket.on('now', data => {
      this.setState({
        message: data.message
      })
    })
  }

  render () {
    return (
      <div>
        {this.state.message}
      </div>
    )
  }
}

export default ChatOne

启动后我遇到了这个错误。我问这个问题是关于这个问题的错误

enter image description here

1 个答案:

答案 0 :(得分:0)

您的第一个<App />渲染器将没有this.state.socket,因为它在挂载之前不会设置。

render () {
  const { socket } = this.state;

  if(!socket) {
    return <div>Loading...</div>
  }

  const { Component, pageProps } = this.props

  return <Component {...pageProps} socket={socket} />
}