javascript - 无法使用 React Native 将 Socket io 连接到 https

标签 javascript reactjs socket.io react-native ssl-certificate

我正在尝试设置我的应用程序与 socket.io 聊天并使用 https。它在我使用 http 时有效,但由于安全原因已更改,我无法再连接到我的聊天服务器。

其实应该没什么可做的,也许有人遇到过类似的问题?

从我的 Web 前端连接到我的聊天服务器效果很好,但尝试下面的代码无法连接到 Android 和 iOS:

import './UserAgent.js';
import io from 'socket.io-client/socket.io';

const connectionOptions = {
  jsonp     : false,
  transports: ['websocket'],
  secure    : true
};

export class App extends Component {

  constructor() {
    super();
    this.state = {
        chatThings: ''
    };

    this.chatUrl = 'https://chat.foo.info';
    this.socket  = io(this.chatUrl, connectionOptions)
  }

  connectToChatServer() {

    let tries = 0;
    var that  = this;
    setInterval(()=> {
        that.socket.connect(that.chatUrl, connectionOptions);
        console.log('CHAT url', that.chatUrl);
        if (that.socket.connected) {
            alert('Finally CONNECTED!!!!!!');
            that.setState({
                connected: socket.connected
            });

        }
        tries = tries + 1;
    }, 2500);

    this.socket.on('error', (err)=> {
        console.log('CHAT: error', err);
    });
}

使用最新的 ReactNative 和最新的 socket.io

更新

window.navigator.userAgent = 'ReactNative';

var io = require('../node_modules/socket.io-client/dist/socket.io');

// -----------------------------------------------------------------------------------------------------------------
// Chat
// -----------------------------------------------------------------------------------------------------------------

Backend.prototype.connectToChatServer = function () {
  let self = this;
  this.dispatch(Actions.connectToChatServer());

  const connectionOptions = {
    jsonp     : false,
    secure    : true,
    transports: ['websocket']
  };

  log.info('CHAT IO CONNECTION');
  this.socket = io(this.chatUrl, connectionOptions);
  function authenticate() {
    self.socket.emit('authenticate', {token: Store.getState().User.token});
  }

........

实际上,我唯一改变的是更新套接字 io 并根据最新版本做出 native react ,并使用 ReactNative 的 UserAgent。我希望这对任何人都有帮助

"socket.io-client": "^1.7.1",
"react-native": "^0.29.2", // this version worked, i have tested it on RN 43 too which works as well

最佳答案

您是否尝试过将证书放入您的应用程序中? 有关详细信息,请参阅此博客:https://blog.synyx.de/2010/06/android-and-self-signed-ssl-certificates/

关于javascript - 无法使用 React Native 将 Socket io 连接到 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38094844/

相关文章:

javascript - 如何使用 @testing-library/react-native 在 react-native 中测试 TextInput?

javascript - 无法设置远程应答 sdp : Called in wrong state: stable

javascript - 如何从 express 应用程序中获取 http.server?

javascript - PHP 和 JQuery 照片上传和裁剪问题

javascript - 异步失败时更喜欢抛出或拒绝

javascript - 如何使用 jest/enzyme 测试 useEffect 与 useDispatch Hook 的结合?

reactjs - 如何在 formik 中使用 React 数字格式

node.js - Flutter Socket io 几秒钟后断开连接

javascript - 如何使用 React 路由器将重定向重写为普通路由?

javascript - 使用 NodeJS 构建 Dojo - 无法生成图层