W
W
Wasya UK2019-04-30 13:07:09
Node.js
Wasya UK, 2019-04-30 13:07:09

Why is there no connection to websockets?

I made a simple server, checked connect and emit, everything works. Then he made an attempt to connect and send a message through react-native, but neither connection nor message was written in the server console. On a simple html page, I connected like this: var socket = io('http://localhost:3000/');it didn’t work in react-native. Then I decided to use a connection using ws , but that didn't help either. What is the problem?
NODE

io.on('connection', function(socket){
  console.log('an user connected');

  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
  });

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

HTML
<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", ready);

    function ready() {
      var socket = io('http://localhost:3000/');

      setInterval(() => {
        socket.emit('chat message', "$('#m').val()");
      }, 3000);
    }
  </script>

REACT NATIVE
import React, { Component } from "react";
import { View, Text } from "react-native";

export default class RemoteControl extends Component {
  constructor(props) {
    super(props);

    this.state = {
      open: false,
      connected: false
    };

    this.socket = new WebSocket('ws://10.0.2.2:3000/');
    this.socket.onopen = () => {
      this.setState({connected:true})
    };
  }

  emit = () => {
    if( this.state.connected ) {
      this.socket.send("chat message")
      this.setState(prevState => ({ open: !prevState.open }))
    }
  }

  componentDidMount() {
        this.socket.onopen = () => this.socket.send(JSON.stringify({type: 'chat message', payload: 'Hello Mr. Server!'}));
        this.socket.onmessage = ({data}) => console.log(data);
    }

  render() {
    return (
      <View>
        <Text>Remote control page</Text>
      </View>
    );
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question