React Native Websocket JSON通信

时间:2017-06-15 09:13:02

标签: android json react-native websocket

我正在尝试建立一个通过JSON与websever通信的Websocket客户端。我没有在网上找到任何好的例子。

我只在网上找到了这个代码:

var ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened
  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

我不知道如何将此代码集成到我的应用代码中以实现功能。 我需要为它安装一些软件包吗? 我正在为我的学习做一个项目,最后我应该有一个Quiz-App连接到服务器来获取游戏的问题和答案。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

You do not need anything else to work with a WebSocket in react-native (or any relatively new JS environment for that matter). The example that you found covers pretty much anything that you need to get started. The next step is to bind that to your React logic. For instance, you can create a WebSocketController component that would look (details omitted) like this

class WebSocketController extends React.Component {
  componentDidMount(){
    this.ws = new WebSocket('ws://host.com/path');
    this.ws.onmessage = this.handleMessage.bind(this);
    this.ws.onerror = //...
  }
  handleMessage(e){
    // dispatch event (á la redux, flux), or do something else
  }
  componentWillUnmount(){
    // close WS
  }
}

Render this within your React hierarchy and it will be started along the rest of your components. If you need something more specific, let us know.