socket.io-client 在 react-native 中使用时保持连接 [英] socket.io-client keeping on connecting when using in react-native

查看:121
本文介绍了socket.io-client 在 react-native 中使用时保持连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 RN 项目中使用 websocket.我使用服务器端的 ws 和 RN 内置的 websocket 实现来做到这一点.但是好像不太方便,因为我之前用过 socket.io.所以我尝试使用socket.io:在注册护士:

I want to use the websocket in my RN project. And I did it using the ws at server side and the RN built-in websocket implementation. But it seems not so convinient since I use socket.io before. So I tried to use socket.io: In RN:

import './userAgent'
import io from "socket.io-client/socket.io"

在组件中:

    componentDidMount() {
     this.socket = io('https://localhost:4080',{jsonp: false});
     this.socket.on('hello', (msg) =>{
       this.setState({response:msg})

     });
    }

在服务器中:

  io.on('connection', function(socket){
   socket.emit('hello','hello world')
   console.log('a user connected');
   socket.on('disconnect',function(){
     console.log('user disconnected')
   })
  })

在 userAgent.js 中

And in userAgent.js

window.navigator.userAgent = 'react-native';

这只是我用谷歌搜索的结果,他们说它会起作用.但对我来说,chrome 调试器停在:

That is just the result I googled and they said it will work. But for me, the chrome debugger stopped at:

function load() {
 var r;
 try {
  r = exports.storage.debug;
 } catch(e) {}
 return r;
}

它说存储没有定义.然后我查看socket.io.js,发现exports.storage是window.localStorage.所以我禁用了远程js调试,代码开始运行.

And it says the storage is not defined. Then I looked into the socket.io.js and find that the exports.storage is window.localStorage. So I disabled the remote js debug, and the code began running.

但服务器继续登录:有用户连接.好像我的 RN 应用程序一直在连接到服务器.而且似乎 socket.on() 在客户端不起作用.

But the server continues to log : a user connected . as if my RN app is keeping on connecting to the server. And it seems the socket.on() did not work at client side.

react-native 版本:0.27.2

react-native version:0.27.2

socket.io-client 版本:1.4.8

socket.io-client version:1.4.8

有人知道哪里出了问题吗?

Anyone knows where is going wrong?

推荐答案

嗯,终于在翻看socket.io源码后找到了解决方案.似乎 socket.io 默认不使用websocket"作为传输.在我的情况下它将使用轮询",因此只需明确设置它:

Well,finally I found the solution after looking through the socket.io source. It seems that the socket.io does not use 'websocket' as transport defaultly. It will use the 'polling' in my case, so just explicityly set it :

 componentDidMount() {
    var socket = io('http://localhost:4080', { jsonp: false, transports: ['websocket'] })
    socket.on('hello', (msg) => {
       //do something
    });
}

现在可以了.但仍然让我感到困惑的是,在浏览器客户端中,我没有设置传输,它运行良好,但在 react-native 中却没有.不知道为什么.

Now it works. But what still confuses me is that in brower client I do not set the transports and it just work well but in react-native it doesn't. Not figured out why.

这篇关于socket.io-client 在 react-native 中使用时保持连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆