iOS模拟器上的React-Native无法真正连接到socket.io

问题描述

我发现了许多类似的问题,但是没有一个答案对我有进一步的帮助。

我要实现的目标
使用Socket.io与React-Native聊天的应用程序

问题
Socket.io服务器说客户端一直在断开连接/断开连接。

最令人不安的(至今仍给人希望的)事实是:这已经起作用-一个晚上。那时我做了一个quick video,所以这就是我的目标。

服务器日志:

[nodemon] starting `ts-node -r esm index.ts`
  nodemon:run spawn sh -c ts-node -r esm index.ts +0ms
  nodemon bus new listener: exit (0) +7ms
  nodemon bus new listener: exit (0) +1ms
  nodemon:run start watch on: [ '*.*',re: /.*\..*/ ] +1ms
  nodemon start watch on: /Users/kevin/Projects/api +83ms
  nodemon ignored [
  '**/.git/**','**/.nyc_output/**','**/.sass-cache/**','**/bower_components/**','**/coverage/**','**/node_modules/**',re: /.*.*\/\.git\/.*.*|.*.*\/\.nyc_output\/.*.*|.*.*\/\.sass\-cache\/.*.*|.*.*\/bower_components\/.*.*|.*.*\/coverage\/.*.*|.*.*\/node_modules\/.*.*/
] +0ms
  nodemon:watch chokidar watching: /Users/kevin/Projects/api/eslintrc.json +0ms
  nodemon:watch chokidar watching: /Users/kevin/Projects/api/index.ts +0ms
  nodemon:watch chokidar watching: /Users/kevin/Projects/api/package-lock.json +0ms
  nodemon:watch chokidar watching: /Users/kevin/Projects/api/package.json +0ms
  nodemon:watch chokidar watching: /Users/kevin/Projects/api/tsconfig.json +0ms
  nodemon:watch chokidar watching: /Users/kevin/Projects/api/types/socket.io/types.ts +2ms
  nodemon watch is complete +14ms
  socket.io:server initializing namespace / +0ms
  socket.io-parser encoding packet {"type":0,"nsp":"/"} +0ms
  socket.io-parser encoded {"type":0,"nsp":"/"} as 0 +0ms
  socket.io:server creating engine.io instance with opts {"path":"/socket.io","initialPacket":["0"]} +1ms
  socket.io:server attaching client serving req handler +39ms
  engine intercepting request for path "/socket.io/" +0ms
  engine handling "GET" http request "/socket.io/?EIO=3&transport=polling&t=NIeBUJ9" +0ms
  engine handshaking client "4H-IpKU9ByLaXFZkAAAA" +3ms
  engine:socket sending packet "open" ({"sid":"4H-IpKU9ByLaXFZkAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}) +0ms
  engine:socket sending packet "message" ([ '0' ]) +0ms
  engine:polling setting request +0ms
  engine:socket flushing buffer to transport +2ms
  engine:polling writing "97:0{"sid":"4H-IpKU9ByLaXFZkAAAA","pingTimeout":60000}2:40" +1ms
  engine:socket executing batch send callback +6ms
  socket.io:server incoming connection with id 4H-IpKU9ByLaXFZkAAAA +10s
  socket.io:client connecting to namespace / +1ms
  socket.io:namespace adding socket to nsp / +0ms
  socket.io:socket socket connected - writing packet +2ms
  socket.io:socket joining room 4H-IpKU9ByLaXFZkAAAA +1ms
  socket.io:socket packet already sent in initial handshake +0ms
Connected: 4H-IpKU9ByLaXFZkAAAA
  socket.io:socket joined room [ '4H-IpKU9ByLaXFZkAAAA' ] +1ms

// This is the first connection. It stays on this state for ~10s.

  engine intercepting request for path "/socket.io/" +21s
  engine handling "GET" http request "/socket.io/?EIO=3&transport=polling&t=NIeBZUT" +0ms
  engine handshaking client "M3PZY977msXP-JreAAAB" +1ms
  engine:socket sending packet "open" ({"sid":"M3PZY977msXP-JreAAAB","pingTimeout":60000}) +21s
  engine:socket sending packet "message" ([ '0' ]) +0ms
  engine:polling setting request +21s
  engine:socket flushing buffer to transport +0ms
  engine:polling writing "97:0{"sid":"M3PZY977msXP-JreAAAB","pingTimeout":60000}2:40" +1ms
  engine:socket executing batch send callback +1ms
  socket.io:server incoming connection with id M3PZY977msXP-JreAAAB +21s
  socket.io:client connecting to namespace / +0ms
  socket.io:namespace adding socket to nsp / +0ms
  socket.io:socket socket connected - writing packet +0ms
  socket.io:socket joining room M3PZY977msXP-JreAAAB +0ms
  socket.io:socket packet already sent in initial handshake +0ms
Connected: M3PZY977msXP-JreAAAB
  socket.io:socket joined room [ 'M3PZY977msXP-JreAAAB' ] +1ms

// This is the second connection. It stays again on this state for ~10s and keeps repeating.

  engine intercepting request for path "/socket.io/" +21s
  engine handling "GET" http request "/socket.io/?EIO=3&transport=polling&t=NIeBef7" +0ms
  engine handshaking client "48q2S3j64VNsGsPVAAAC" +0ms
  engine:socket sending packet "open" ({"sid":"48q2S3j64VNsGsPVAAAC","pingTimeout":60000}) +21s
  engine:socket sending packet "message" ([ '0' ]) +0ms
  engine:polling setting request +21s
  engine:socket flushing buffer to transport +1ms
  engine:polling writing "97:0{"sid":"48q2S3j64VNsGsPVAAAC","pingTimeout":60000}2:40" +0ms
  engine:socket executing batch send callback +0ms
  socket.io:server incoming connection with id 48q2S3j64VNsGsPVAAAC +21s
  socket.io:client connecting to namespace / +0ms
  socket.io:namespace adding socket to nsp / +0ms
  socket.io:socket socket connected - writing packet +0ms
  socket.io:socket joining room 48q2S3j64VNsGsPVAAAC +0ms
  socket.io:socket packet already sent in initial handshake +0ms
Connected: 48q2S3j64VNsGsPVAAAC
  socket.io:socket joined room [ '48q2S3j64VNsGsPVAAAC' ] +1ms

我尝试过的事情

  • 添加window.navigator.userAgent = "react-native";
  • dist文件夹中导入socket.io-client:'socket.io-client/dist/socket.io'
  • 使用我的本地IPv4 const socket = io('http://IPv4:3000');,但在我的情况下,它可以与io('http://localhost:3000);一起使用
  • 向客户端调用jsonp: falsetransports: ['websocket'] pingTimeout: 30000,pingInterval: 30000
  • 添加选项
  • 使用socket.io和socket.io-client v2.0.3(因为据称它应该适用于RN)(但在我的情况下,它适用于v2.3.0
  • 使用打字稿
  • (使用RN CLI初始化工具)启动一个全新的RN项目
  • 通过网络连接
    • 这成功完成了,所以我认为后端很好。因此,我不确定这是否可以完全消除后端的问题...听起来像是,好像这排除了后端并在客户端或模拟器上暴露了问题(端口被阻塞) ?兼容性问题?但是为什么突然之间...)
  • 3000的端口不同
  • 使用node代替esm

当我“ React-Nativefied”(即div-> View等...)时,我发现有些奇怪的事情this small guide(我只是想在我的代码中找到与其他人的代码间的差异),更改房间似乎可以正常工作!但是,仍然没有再收到消息,并且断开连接仍然发生。

每当我在客户端中登录socket.connected时,它总是返回false ...

一个小注解:自从这个问题开始发生以来,我的模拟器的Fast-Refresh不再起作用。我总是需要手动刷新。在其他项目中不会发生这种情况。

我将添加我的代码(它仍然非常疯狂):

后端
index.ts

import { Message,Socket } from './types/socket.io/types';

const http = require('http').createServer().listen(3000);
const io = require('socket.io').listen(http);

io.on(Socket.Connection,(socket) => {
  console.log(`Connected: ${socket.id}`);
  socket.on(Socket.disconnect,() => console.log(`disconnected: ${socket.id}`));
  socket.on('error',(error) => console.log(`ERROR: ${error}`));
  socket.on(Socket.Join,() => {
    console.log(`Socket ${socket.id} joining`);
    socket.join();
  });
  socket.on(Socket.ChatMessage,(data: { message: Message }) => {
    const { message } = data;
    io.emit('chatMessage',message);
  });
});

types / socket.io / types.ts

export enum Socket {
  Connection = 'connection',disconnect = 'disconnect',Join = 'join',ChatMessage = 'chatMessage',}

export type Message = string;

前端
src / App.tsx

import React,{ useEffect,useState } from 'react';
import {
  View,Text,StyleSheet,TextInput,TouchableWithoutFeedback,} from 'react-native';
import {
  initiateSocket,subscribetochat,disconnectSocket,sendMessage,} from './helpers/socket.io';

import { Message } from './types/socket.io/types';

const App: React.FC = () => {
  const [messageInputValue,setMessageInputValue] = useState('');
  const [chatMessages,setChatMessages] = useState<Message[]>([]);
  useEffect(() => {
    initiateSocket();
    subscribetochat((error: Error | null,newChatMessage: Message) => {
      console.log('error is ',error);
      if (error) {
        return;
      }
      setChatMessages((prevIoUsChatMessages: Message[]) => [
        ...prevIoUsChatMessages,newChatMessage,]);
    });
    return () => {
      disconnectSocket();
    };
  },[]);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Live Chat:</Text>
      <TextInput
        value={messageInputValue}
        onChangeText={(inputValue) => setMessageInputValue(inputValue)}
      />
      <TouchableWithoutFeedback
        onPress={() => {
          sendMessage(messageInputValue);
          setMessageInputValue('');
        }}
      >
        <Text>Send</Text>
      </TouchableWithoutFeedback>
      <View style={styles.textContainer}>
        {chatMessages.map((message,index) => (
          <Text key={`${message}_${index}`}>{message}</Text>
        ))}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingTop: 100,flex: 1,backgroundColor: '#F5FCFF',},title: {
    fontSize: 24,textContainer: {
    marginTop: 12,});

export default App;

src / helpers / socket.io / index.ts

import io from 'socket.io-client';
import { Message,Socket } from '../../types/socket.io/types';

let socket: SocketIOClient.socket;

export const initiateSocket = () => {
  socket = io('http://localhost:3000');
  console.log(`Connecting socket...`);
  if (socket) {
    socket.emit(Socket.Join);
  }
};
export const disconnectSocket = () => {
  console.log('disconnecting socket...');
  if (socket) {
    socket.disconnect();
  }
};
export const subscribetochat = (
  callBack: (error: Error | null,newChatMessage: Message) => void,) => {
  if (!socket) {
    return true;
  }

  socket.on(Socket.ChatMessage,(message: Message) => {
    return callBack(null,message);
  });
};
export const sendMessage = (message: Message) => {
  if (socket) {
    socket.emit('chatMessage',{ message });
  }
};

编辑

它再次工作了很短的时间,我必须检查socket.io日志中的差异到底是怎么回事。比较不同之处就是结果(左无效,右有效):

Difference in socket.io logs

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)