tiaanduplessis/react-native-websocket

How to listen and send a message ?

Opened this issue · 2 comments

I'm new to React Native . here is the example of use below :

import React, { Component } from 'react'
import { AppRegistry, View } from 'react-native'
import WS from 'react-native-websocket'

export default class Example extends Component {

  render () {
    return (
      <View style={{flex: 1}}>
        <WS
          ref={ref => {this.ws = ref}}
          url="wss://echo.websocket.org/"
          onOpen={() => {
            console.log('Open!')
            this.ws.send('Hello')
          }}
          onMessage={console.log}
          onError={console.log}
          onClose={console.log}
          reconnect // Will try to reconnect onClose
        />
      </View>
    )
  }
}

I encounter two problems to know:

1- how do we listen to the messages that the server sends back and process them?
2- how to send a message to the server outside the WS component

Thank you for your answers

in terms of listening to messages sent by servers, I understood how to do it:

 onMessage={event => {
            console.log('data send websocket : ', event.data);
          }}

now how to send a message to the server outside the WS component ?

now how to send a message to the server outside the WS component ?

If you're still looking for the answer, I guess you should use ref that is assigned on the first line of the WS component:

this.ws.send("some data here")

as the component is essentially just a wrapper around the WebSocket object.