将 Socket.io 与 React Native 一起使用但不起作用 [英] Using Socket.io with React Native and not working
问题描述
我正在尝试完成作业,我需要为此使用 websocket.我使用 react native 作为客户端,使用 node.js 作为服务器.但是,即使我尝试了网络上的所有解决方案建议,也无法使其正常工作.
I'm trying to complete a homework and I need to have websocket for it. I use react native as client and node.js for server. However, even I tried all the solution suggestions on web, I couldn't get it working.
客户
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');
});
}
服务器
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');
});
});
这是我使用的版本,
socket.io: 2.1.1
socket.io: 2.1.1
快递:4.16.4
socket.io 客户端:2.1.1
socket.io-client: 2.1.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);
我在函数调用中省略了 connectionConfig 并更改了我将本地主机写入的方式.
I've omitted the connectionConfig from the function call and change the way I write the local host to that.
this.socket = SocketIOClient('http://192.168.xxxx:3000');>
this.socket = SocketIOClient('http://192.168.xxxx:3000');
它现在适用于安卓和 iOS.
It now works both on android and iOS.
这篇关于将 Socket.io 与 React Native 一起使用但不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!