Websockets代码错误

时间:2018-05-25 11:22:02

标签: react-native websocket

我开始使用React Native中的websockets,遵循以下文章:

https://medium.com/dailyjs/combining-react-with-socket-io-for-real-time-goodness-d26168429a34

写得很好,如果能让它工作的话,应该给我一个良好的基础。我认为代码是为React创建的,但希望它可以与React Native一起使用。

我已经复制了3个文件的代码并且它运行没有错误(服务器和客户端)但App.js客户端没有更新,它只显示来自服务器的计时器值:暂无时间戳'

我使用以下方法创建了应用程序: create-react-native-app socket-timer

在我安装的新目录中: npm i --save socket.io 然后 npm i --save socket.io-client

我的3个文件是:

server.js https://pastebin.com/zgp6pdjq

const io = require('socket.io')();

io.on('connection', (client) => {
  client.on('subscribeToTimer', (interval) => {
  console.log('client is subscribing to timer with interval ', interval);
setInterval(() => {
  client.emit('timer', new Date());
}, interval);
});
});

const port = 8000;
io.listen(port);
console.log('listening on port ', port);

api.js https://pastebin.com/aLiiyMU1

import openSocket from 'socket.io-client';

const  socket = openSocket('http://localhost:8000');

function subscribeToTimer(cb) {
  socket.on('timer', timestamp => cb(null, timestamp));
  socket.emit('subscribeToTimer', 1000);
}

export { subscribeToTimer };

App.js https://pastebin.com/vxfWEaPz

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { subscribeToTimer } from './api';

export default class App extends React.Component {

constructor(props) {
  super(props);
  subscribeToTimer((err, timestamp) => this.setState({ 
    timestamp 
  }));
}

state = {
  timestamp: 'no timestamp yet'
};

  render() {
    return (
      <View style={styles.container}>
        <Text>Timer value from the server: {this.state.timestamp}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

我在一个控制台窗口中启动服务器:节点服务器 我在另一个控制台窗口启动客户端应用程序: npm start (然后在Android设备上使用Expo启动它)

如果你能为我查看它会很棒,因为我没有看到任何错误(我已经检查过PC防火墙上的端口8000已打开)

1 个答案:

答案 0 :(得分:0)

这是app.js中的这一行:

const socket = openSocket(&#39; localhost:8000&#39;);

我将其更改为笔记本电脑的IP地址:

const socket = openSocket(&#39; 192.168.1.94:8000&#39;);

说实话,我不知道它为什么不能处理localhost。我猜它一定与世博会有关。