P
P
Praud2018-02-18 19:50:16
JavaScript
Praud, 2018-02-18 19:50:16

How to work with web sockets in react-native?

Good Sunday evening everyone. I FE dev
decided to look at React native.
Launched a server on EC2 (AWS).
Wrote this code

const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', (req, res) => {
   res.send('Hello world!');
})

io.on('connection', (socket) => {
  socket.on('start', () => {
    socket.emit('begin', true);
  });
});
server.listen(3000, () => console.log('Server started!'));

Wrote a lightweight component in react-native
....
buttonHandle = () => {
    const socket = io("ws://blablabla/");
    socket.emit('start');
    socket.on('begin', function (data) {
      console.warn(data);
    });
  }

  render() {
    return (
      <View style={styles.container}>
      <Text style={styles.boom}>Boom!</Text>
      <Button title='Activate' onPress={this.buttonHandle} />
      </View>
    );
  }

And so console.warn is not highlighted. At the same time, it seems like the request is being processed in the Expo network.
I tried the same code on the client as in the click handler on a regular html5 page and in the browser it displays "true" in the console. What am I doing wrong in React-native ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Praud, 2018-02-20
@Praud

Guys, any ideas? I'm still stacked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question