React native iOS模拟器上的本机反应未真正连接到socket.io
我发现了许多类似的问题,但没有一个答案对我有任何帮助 我正在努力实现的目标React native iOS模拟器上的本机反应未真正连接到socket.io,react-native,websocket,socket.io,ios-simulator,React Native,Websocket,Socket.io,Ios Simulator,我发现了许多类似的问题,但没有一个答案对我有任何帮助 我正在努力实现的目标 使用Socket.io与React Native的聊天应用程序 问题 Socket.io服务器表示客户端一直在断开/断开连接 最令人不安(但给人以希望)的事实是:这已经奏效了——已经有一个晚上了。我当时做了一个,所以这就是我的目标 服务器日志: [nodemon] starting `ts-node -r esm index.ts` nodemon:run spawn sh -c ts-node -r esm ind
使用Socket.io与React Native的聊天应用程序 问题
Socket.io服务器表示客户端一直在断开/断开连接 最令人不安(但给人以希望)的事实是:这已经奏效了——已经有一个晚上了。我当时做了一个,所以这就是我的目标 服务器日志:
[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","upgrades":["websocket"],"pingInterval":25000,"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","upgrades":["websocket"],"pingInterval":25000,"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","upgrades":["websocket"],"pingInterval":25000,"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","upgrades":["websocket"],"pingInterval":25000,"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","upgrades":["websocket"],"pingInterval":25000,"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:false
传输:['websocket']
pingTimeout:30000,pingInterval:30000
- 使用socket.io和socket.io-client v2.0.3(因为据称这应该适用于RN)(但在我的例子中,它适用于v2.3.0)
- 不使用打字脚本
- 启动一个全新的RN项目(使用RN CLI初始化工具)
- 通过网络连接
- 这是成功的,所以我假设后端是好的。所以我不确定这是否完全消除了后端上的问题…听起来好像这排除了后端,并暴露了客户端或模拟器上的问题(端口阻塞?兼容性问题?但为什么突然…)
- 与
3000不同的端口
- 使用
代替节点
esm
索引 类型/socket.io/types.ts 前端
src/App.tsx 编辑 在很短的一段时间内,它再次发挥了作用,我检查了socket.io日志中的差异,到底有什么不同。比较差异这就是结果(左不起作用,右起作用):
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);
});
});
export enum Socket {
Connection = 'connection',
Disconnect = 'disconnect',
Join = 'join',
ChatMessage = 'chatMessage',
}
export type Message = string;
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;
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 });
}
};