如果不将客户端的服务器uri传递给io(),则无法使用SocketIO
我对React非常陌生。我使用Universal rendering来构build一个简单的React web应用程序。 我也使用socket.io实时更新一些信息。
在socket.io文档中,它指出您可以通过执行以下操作build立与服务器的连接:
const socket = io()
在客户端。 但是,这不适合我。 我从socket.io-client得到这个错误:
if (null == uri) uri = loc.protocol + '//' + loc.host; ^ TypeError: Cannot read property 'protocol' of undefined
相反,我必须把uri传给io()像这样:
const socket = io('http://localhost:5050')
然后一切按预期工作…我的问题是如何build立socket.io通过简单地做第一个例子const socket = io()
(没有IP地址/端口的服务器)
这是我的server.js:
require('babel-register') const express = require('express') const React = require('react') const ReactDOMServer = require('react-dom/server') const ReactRouter = require('react-router') const ServerRouter = ReactRouter.ServerRouter const socketIO = require('socket.io') const http = require('http') const _ = require('lodash') const fs = require('fs') var bodyParser = require('body-parser') const PORT = 5050 const baseTemplate = fs.readFileSync('./index.html') const template = _.template(baseTemplate) const App = require('./js/App').default const app = express() var server = http.createServer(app) var io = socketIO(server) // middleware app.use(bodyParser.json()) app.set('socketio', io) app.use('/public', express.static('./public')) app.use((req, res) => { const context = ReactRouter.createServerRenderContext() const body = ReactDOMServer.renderToString( React.createElement(ServerRouter, {location: req.url, context: context}, React.createElement(App) ) ) res.write(template({body: body})) res.end() }) console.log('listening on port', PORT) server.listen(PORT)
和我的sockets组件:
import React, { Component } from 'react' const {string, bool, object} = React.PropTypes const io = require('socket.io-client') const socket = io('http://localhost:5050') // I want to change this! class WelcomeMsg extends Component { constructor (props) { super(props) this.state = { text: '' } } componentDidMount () { socket.on(this.props.location.pathname, (mesg) => { this.setState({text: mesg}) }) } componentWillUnmount () { socket.off(this.props.page) } render () { <div> {this.state.text} </div> } export default WelcomeMsg
事实certificate,毕竟,如果我这样设定,
import React, { Component } from 'react' const {string, bool, object} = React.PropTypes const io = require('socket.io-client') let socket class WelcomeMsg extends Component { constructor (props) { super(props) this.state = { text: '' } } componentDidMount () { socket = io() socket.on(this.props.location.pathname, (mesg) => { this.setState({text: mesg}) }) } componentWillUnmount () { socket.off(this.props.page) } render () { <div> {this.state.text} </div> } export default WelcomeMsg
基本上,如果我在组件安装后初始化套接字。 我猜这个组件需要挂载才能获得默认地址连接。