无法使用 Socket io 连接到带有 React Native 的 https

Big*_*n86 5 javascript ssl-certificate socket.io reactjs react-native

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

实际上不应该有太多的事情要做,也许有人遇到过类似的问题?

从我的 Web-Frontend 连接到我的聊天服务器效果很好,但尝试下面的代码不能连接 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);
    });
}
Run Code Online (Sandbox Code Playgroud)

使用最新的 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});
  }

........
Run Code Online (Sandbox Code Playgroud)

实际上,我唯一改变的是更新套接字 io 并对最新版本做出本机反应,并使用 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
Run Code Online (Sandbox Code Playgroud)

小智 1

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