【问题标题】:WebSocket React NativeWebSocket 反应本机
【发布时间】:2018-07-10 15:08:16
【问题描述】:

我是 react native 的新手,从 ReactJS 迁移到我认为我可以使用与我之前的纯 Reactjs 应用程序相同的软件包,但我错了。

我要做的是建立一个websocket 连接。

我最近在我的 ReactJS 应用程序中使用 autobahnJSWAMP2,但是当我转向 react native 时,似乎 autobahnJS 不支持 react-native

connectToSocketFunction = () =>{ // autobahn code
        let connection = new autobahn.Connection({ url: 'wss://api.example.com/websocket/', realm: 'Realm1', authmethods: ['jwt'] });
        connection.onopen = (session, detalis) => {

            session.subscribe('ChannelName', (data)=>console.log(data));
        };

有谁知道 react native 如何根据我的代码建立套接字连接?

我试过react-native-autobahnjs 不起作用

【问题讨论】:

    标签: javascript reactjs react-native websocket autobahn


    【解决方案1】:

    React Native 文档提到了对 WebSocket 连接的支持:

    var ws = new WebSocket('ws://host.com/path');
    
    ws.onopen = () => {
      // connection opened
      ws.send('something'); // send a message
    };
    
    ws.onmessage = (e) => {
      // a message was received
      console.log(e.data);
    };
    
    ws.onerror = (e) => {
      // an error occurred
      console.log(e.message);
    };
    
    ws.onclose = (e) => {
      // connection closed
      console.log(e.code, e.reason);
    };
    

    https://facebook.github.io/react-native/docs/network.html#websocket-support

    您很可能需要使用其他基于 React Native 的框架来填补 Autobahn 提供的空白,例如会话支持和 JWT 身份验证。

    【讨论】:

    • 你知道有什么框架可以像高速公路一样填补空白吗?
    • 这将需要几个不同的框架和代码 sn-ps,这将超出这个问题的范围。你也可以 fork AutoBahnJS 并修改它以使用 React Native。 Here's AutoBahn GitHub 上打开的一个问题,它解释了您需要做什么。
    • 感谢亚历克斯的帮助
    • 链接不再起作用,对于任何需要它的人reactnative.dev/docs/network#websocket-support
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 2018-03-02
    • 2020-08-10
    • 2016-04-18
    • 2021-12-26
    • 2019-05-11
    相关资源
    最近更新 更多