Search code examples
javascriptreactjsreact-nativewebsocketautobahn

WebSocket React Native


I'm new to react native moved from ReactJS I thought I can use same packages as my previous pure Reactjs app but I was wrong.

What I'm trying to do is to make a websocket connection.

I'm recently using autobahnJS package WAMP2 in my ReactJS app but when I moved to react native it seems autobahnJS doesn't support 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));
        };

Anyone know how does react native make socket connection based on my code?

I have tried react-native-autobahnjs doesn't work


Solution

  • The React Native documentation mentions support for WebSocket connections:

    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

    You will most likely need to use other React Native based frameworks to fill in the gaps that Autobahn provided, e.g. session support and JWT authentication.