[英]Using Socket.io with React Native and not working
I'm trying to complete a homework and I need to have websocket for it. 我正在尝试完成一项功课,我需要为它设置websocket。 I use react native as client and node.js for server. 我使用react native作为客户端,node.js作为服务器。 However, even I tried all the solution suggestions on web, I couldn't get it working. 然而,即使我在网上尝试了所有的解决方案建议,我也无法让它发挥作用。
Client 客户
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import SocketIO from 'socket.io-client';
const connectionConfig = {
jsonp: false,
reconnection: true,
reconnectionDelay: 100,
reconnectionAttempts: 100000,
transports: ['websocket'], // you need to explicitly tell it to use websockets
};
export default class App extends React.Component {
constructor() {
super();
this.socket = SocketIO('http://localhost:3000',connectionConfig);
this.socket.on('connect', () => {
console.log('connected to server');
});
}
Server 服务器
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const port = 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
server.listen(port, () => {
console.log(port, 'is up');
});
io.on('connection', (socket) => {
console.log('new user connected');
socket.on('disconnect', () => {
console.log('User was disconnected');
});
});
Here are the version I am using, 这是我正在使用的版本,
socket.io: 2.1.1 socket.io:2.1.1
express: 4.16.4 表达:4.16.4
socket.io-client: 2.1.1 socket.io-client:2.1.1
expo: 30.0.1 世博会:30.0.1
I want to thank you in advance for all your effort. 我想提前感谢您的所有努力。
I have found the solution to my problem. 我找到了解决问题的方法。
this.socket = SocketIO(' http://localhost:3000 ',connectionConfig); this.socket = SocketIO(' http:// localhost:3000 ',connectionConfig);
I've omitted the connectionConfig from the function call and change the way I write the local host to that. 我从函数调用中省略了connectionConfig,并改变了我写本地主机的方式。
this.socket = SocketIOClient(' http://192.168.xxxx:3000 '); this.socket = SocketIOClient(' http://192.168.xxxx:3000 ');
It now works both on android and iOS. 它现在适用于Android和iOS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.