我在后端使用 socket.io,它在使用 socket.io-client 的 vanilla javascript 的前端工作正常,但是当我尝试通过 React Native 连接 socket.io 时,我收到错误:
Vanilla JS(工作完美):
<script> var socket = io.connect('http://localhost:9092'); socket.on('connect', function() { output('<span class="connect-msg">Client has connected to the server!</span>'); });
React Native 代码:(不工作)
this.socket = io.connect('http://localhost:9092',{ reconnection: true, reconnectionDelay: 500, jsonp: false, reconnectionAttempts: Infinity, transports: ['websocket']}); this.socket.on('connect',function(e){ console.log("on Connect"); }) this.socket.on('connect_error', (err) => { console.log(err) });
错误:
websocket error
Stack trace: node_modules/engine.io-client/lib/transport.js:67:22 in onError
node_modules/engine.io-client/lib/transports/websocket.js:157:17 in onerror node_modules/event-target-shim/lib/event-target.js:172:43 in dispatchEvent
node_modules/react-native/Libraries/WebSocket/WebSocket.js:290:10 in
node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:191:12 in emit
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:349:47 in __callFunction
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:106:26 in
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:297:10 in __guard
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
我正在使用 https://github.com/mrniko/netty-socketio在后端。
已使用 expo-cli 创建了 React Native 应用程序.
最佳答案
尝试获取 IP 而不是使用本地主机 请记住电话和 PC 双方的 IP 应该相同但端口不同,这可能会解决您的错误
this.socket = io.connect(' http://localhost:9092 '}
到
this.socket = io.connect(' http://192.x.x.x.x:9092 '}
关于reactjs - Socket.io 客户端不支持 React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55443912/