在React Native中使用socket.io-client

在react-native中可以使用socket.io-client进行通讯。使用起来也相对较为方便

实战项目

首先使用react-native创建

$ react-native init rnchat

首先cd到你的react-native项目的跟目录下,安装socket.io-client

$ npm install socket.io-client

先运行一下空的项目

$ react-native run-ios

在其他文件中

window.navigator.userAgent = "react-native";


https://github.com/socketio/socket.io/tree/master/examples/chat


window.navigator.userAgent = "react-native";
var io = require('socket.io-client/socket.io');

const socket = io('http://localhost:3000', {
  transports: ['websocket'] // you need to explicitly tell it to use websockets
});

socket.on('connect', () => {
  console.log('connected!');
});