【发布时间】:2018-12-04 15:12:44
【问题描述】:
我正在尝试将 Socket.io 与 react native App 一起使用,但客户端和服务器端之间存在一些问题,我认为代码正确,但单击按钮时它不会更新状态,连接是完成,我显示日志工作我没有显示任何错误!
这是我的代码:
服务器/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
<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.你有一个服务器和两个客户端。如果 Android 项目连接,您应该会在服务器日志中看到两个 id。 2.您将“更新”发送回您的 JS 客户端,而不是您的 react-native 客户端
-
@ChrisG 我在服务器日志中有两个正确的 id,你能用我的代码解释一下你在 Num 2 中的意思吗
-
1.在 Genymotion 设备上打开浏览器并尝试访问服务器。对我来说是
http://192.168.220.10:8080。成功后,将确切的 URL 放入 react 本机代码的io()2. 在您的服务器代码中,将socket.emit("update");更改为io.emit("update");,以便将消息发送给所有客户端 -
@ChrisG 我这样做了,但问题仍然存在:(
-
它对我有用。如果你需要帮助,你需要更具体一点。您是否将 Genymotion 设备设置为桥接模式?你能在 Genymotion 浏览器上看到你快递服务器的 index.html 吗?
标签: javascript reactjs react-native websocket socket.io