在客户端和服务器之间发送消息不好我在 react-native 中使用 socket.io [英] send a message between client and server is not fine i using socket.io in react-native

查看:42
本文介绍了在客户端和服务器之间发送消息不好我在 react-native 中使用 socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Socket.io 与 React Native App 一起使用,但我在客户端和服务器端之间存在一些问题,我认为代码是正确的,但单击按钮时它不会更新状态,连接是完成,我显示日志工作正常我没有显示任何错误!

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!

这是我的代码:

服务器/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");
  });
});

服务器/index.html

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
  }
});

推荐答案

我认为问题出在您的套接字服务器地址上.在 App.js 中你写了 localhost 但如果它是在移动模拟器或设备中,那么你的地址不能是 localhost.它可以是 10.0.2.2 模拟器 Android 或您的电脑和您的设备共享的 WiFi 上的您的电脑地址.

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.

这篇关于在客户端和服务器之间发送消息不好我在 react-native 中使用 socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆