send a message between client and server is not fi

2019-08-27 22:30发布

问题:

I'm trying to use Socket.io with react native App but I have some issue between client side and server side, I think is the code right but it doesn't update the state when clicked the button, the connection is done and I show the log worked I don't show any error in them!

that is my code :

server/app.js

var app = require("express")();
var server = require("http").Server(app);
var io = require("socket.io")(server);

server.listen(8080);

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

io.on("connection", function(socket) {
  console.log(socket.id);
  socket.on("update", () => {
    console.log("update con");
    socket.emit("update");
  });
});

server/index.html

<h1>Welcome Socket.io !!</h1>
<button>Update</button>

<script src="/socket.io/socket.io.js"></script>

<script>
  var socket = io();
  var btn = document.querySelector("button");
  btn.onclick = function() {
    console.log("update func");
    socket.emit("update");
  };
</script>

App.js

import React, { Component } from "react";
import { StyleSheet, Text, View } from "react-native";
window.navigator.userAgent = "react-native";
import io from "socket.io-client";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "HelloWorld"
    };
    this.socket = io("localhost:8080", { jsonp: false });
  }

  componentDidMount() {
    this.socket.on("update", () => {

      this.setState({ name: "updated name !" });
    });
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.instructions}>{this.state.name}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  }
});

回答1:

I think the problem come from the address of your socket server. In App.js you wrote localhost but if it’s in mobile so emulator or device, then your address can’t be localhost. It could 10.0.2.2 for emulator Android or your pc address on the WiFi shared by your pc and your device.