USB调试时App与服务器通信正常,生产环境异常排查求助
问题
我开发的React Native聊天App在USB调试模式下,与服务器的Socket.io通信完全正常,但打包成APK安装到手机后,服务器无法接收App发送的请求。服务器在USB调试测试时运行正常,以下是ChatScreen代码及Logcat日志,请求协助排查。
ChatScreen代码
import React, { useState, useContext, useEffect } from 'react'; import { Text, StyleSheet } from 'react-native'; import { GiftedChat, Bubble } from 'react-native-gifted-chat'; import { AuthContext, useAuth } from '../AuthContext'; import { View, SafeAreaView } from 'react-native'; import { io } from 'socket.io-client'; const ChatScreen = ({route}) => { const { user } = useAuth(); const recipient = route.params.recipient; const [messages, setMessages] = useState([]); const [socket, setSocket] = useState(null); const onSend = (newMessages = []) => { let currentMessage = newMessages[0].text; const sendingMessage = { _id: newMessages[0]._id || Math.random().toString(36).substring(7), text: currentMessage, createdAt: new Date(), user: { _id: user.username, name: user.username, }, }; setMessages((prevMessages) => GiftedChat.append(prevMessages, [sendingMessage])); if (currentMessage.trim() && recipient.trim()) { socket.emit('message', { recipient: recipient, msg: currentMessage }); } }; useEffect(() => { const socketInstance = io('<ip-address>', { query: { userId: user.username }, }); setSocket(socketInstance); socketInstance.on('connect', () => { console.log('Socket connected'); }); socketInstance.on('message', (message) => { const incomingMessage = { _id: message._id || Math.random().toString(36).substring(7), text: message, createdAt: new Date(), user: { _id: recipient, name: recipient, }, }; setMessages((prevMessages) => GiftedChat.append(prevMessages, [incomingMessage])); }); return () => { if (socketInstance) { socketInstance.disconnect(); console.log('Socket disconnected'); } }; }, [recipient, messages]); const renderBubble = (props) => { return ( <Bubble {...props} wrapperStyle={{ left: { backgroundColor: '#f0f0f0', }, right: { backgroundColor: '#007BFF', marginRight: -5, }, }} /> ); }; return ( <SafeAreaView style={{ flex: 1 }}> <Text style={styles.heading}>Your's {user.username == 'test' ? 'test' : 'wow'}</Text> <View style={{ flex: 1, padding: 10 }}> <GiftedChat messages={messages} onSend={(newMessages) => onSend(newMessages)} user={{ _id: user.username, name: user.username, }} renderBubble={renderBubble} /> </View> </SafeAreaView> ); }; const styles = StyleSheet.create({ heading: { fontSize: 24, fontWeight: 'bold', textAlign: 'center', paddingVertical: 10, backgroundColor: '#f0f0f0', }, }); export default ChatScreen;
Logcat日志
01-22 14:53:03.883 15230 15230 D g : setAlphabetAutomaticShiftedKeyboard 01-22 14:53:03.890 15230 15230 D kalsessionstart: com.love 01-22 14:53:03.891 15230 15230 W FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'group'. 01-22 14:53:03.891 15230 15230 W FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'event_map'. 01-22 14:53:03.894 13339 13355 I Finsky : [397405] py.ae(66): com.clusterdev.malayalamkeyboard: Account determined from installer data - [_mpukSYwNRwRnez-YGS3c0h1se5Q8Q5VSQfZFibakUg] 01-22 14:53:03.895 1019 1019 I SDM : HWCDisplayBuiltIn::GetOptimalRefreshRate: active_refresh_rate_: 60 01-22 14:53:03.896 13339 13355 I Finsky : [397405] ljw.a(907): Billing preferred account via installer for com.clusterdev.malayalamkeyboard: [_mpukSYwNRwRnez-YGS3c0h1se5Q8Q5VSQfZFibakUg] 01-22 14:53:03.903 15230 15230 I SoftKeyboard: Starting input. Cursor position = 0,0 01-22 14:53:03.903 15230 15230 D StatsUtils: onStartInputView: 147457 01-22 14:53:03.906 18474 18474 W IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection 01-22 14:53:03.912 18474 18474 W IInputConnectionWrapper: getSelectedText on inactive InputConnection 01-22 14:53:03.912 1019 1019 I SDM : HWCDisplayBuiltIn::GetOptimalRefreshRate: active_refresh_rate_: 60 01-22 14:53:03.913 18474 18474 W IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection 01-22 14:53:03.913 18474 18474 W IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection 01-22 14:53:03.914 15230 15230 E RichInputConnection: Unable to connect to the editor to retrieve text. 01-22 14:53:03.914 15230 15230 D RichInputConnection: Will try to retrieve text later. 01-22 14:53:03.914 18474 18474 W IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection 01-22 14:53:03.914 15230 15230 E RichInputConnection: Unable to connect to the editor to retrieve text. 01-22 14:53:03.914 15230 15230 W RichInputConnection: Unable to connect to the editor. Setting caps mode without knowing text. 01-22 14:53:03.915 18474 18474 W IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection 01-22 14:53:03.915 15230 15230 E RichInputConnection: Unable to connect to the editor to retrieve text. 01-22 14:53:03.915 15230 15230 W RichInputConnection: Unable to connect to the editor. Setting caps mode without knowing text. 01-22 14:53:03.915 15230 15230 D g : requestUpdatingShiftState: autoCapsFlags=sentences recapitalizeMode=undefined
排查与解决建议
- 修正Socket连接地址:代码中
<ip-address>如果是局域网IP,打包后的APK在移动网络下无法访问。需替换为服务器公网IP或域名,同时确保服务器端口已开放公网防火墙权限。 - 添加网络权限:检查
AndroidManifest.xml是否配置网络权限,打包APK默认可能未开启:<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> - 校验Socket连接状态:在
onSend函数中增加Socket连接判断,避免未连接时发送消息:if (currentMessage.trim() && recipient.trim() && socket?.connected) { socket.emit('message', { recipient: recipient, msg: currentMessage }); } else { console.log('Socket未连接,无法发送消息'); } - 优化useEffect依赖项:当前依赖包含
messages,会导致消息更新时频繁重建Socket连接。移除messages,保留recipient和user.username即可:useEffect(() => { // 原连接代码 }, [recipient, user.username]); - 捕获Socket错误日志:添加错误监听,排查连接失败原因:
socketInstance.on('connect_error', (error) => { console.error('Socket连接错误:', error); }); socketInstance.on('disconnect', (reason) => { console.log('Socket断开:', reason); }); - 配置混淆规则:若打包启用了代码混淆,需在
proguard-rules.pro中添加Socket.io的保护规则:-keep class io.socket.** { *; } -keep class com.facebook.react.modules.network.** { *; }
内容的提问来源于stack exchange,提问作者Sandeep pradeep
相关产品推荐
相关产品推荐

