java - (Node.js, socket.io) JSONObject 无法转换为 int
问题描述
我正在尝试创建一个多人游戏,如果大厅未满,则主机有 AI 飞船,它们将它们的动作发送到服务器,服务器将它们的“移动”广播到客户端游戏中的空白飞船。广播伴随着一个“i”,它是 AIShips 标识符,因此正确的船被告知在客户端游戏中移动。
这是使用它的代码:
初始发射:(AIShip.java)
JSONObject data = new JSONObject();
try {
data.put("i", identifier); //Identifier is an int set once in the constructor
gameScreen.spaceSoccer.socket.emit("moveAIShipForward", data);
} catch (JSONException e){
e.printStackTrace();
}
我的服务器:(index.js)
socket.on("moveAIShipForward", function(i) {
socket.broadcast.emit("moveAIShipForward", {id: socket.id, i: i})
});
对广播的响应:(SpaceSoccer.java)
.on("moveAIShipForward", new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject data = (JSONObject) args[0];
try {
int i = data.getInt("i"); //error
gameScreen.AIShip[i].moveBodyForward();
} catch (JSONException e) {
e.printStackTrace();
}
});
错误:W/System.err: org.json.JSONException: Value {"i":0} at i of type org.json.JSONObject 无法转换为 int W/System.err: at org.json.JSON。类型不匹配(JSON.java:100)
解决方案
这是因为您正在嵌套{ "i": identifier }
对象。看一看(在下面的注释代码中解释):
初始发射:(AIShip.java)
JSONObject data = new JSONObject();
...
data.put("i", identifier);
// here the `data` is like `{ "i": 0 }` and it's emmited
gameScreen.spaceSoccer.socket.emit("moveAIShipForward", data);
...
我的服务器:(index.js)
// here, the `i` is what you have sent earlier: `{ "i": 0 }`
socket.on("moveAIShipForward", function(i) {
// here, you are passing the `{ "i": 0 }` object to the new object, under `i` key, the resulting object looks like this:
// `{ id: 0, i: { i: 0 } }`
// and it's emitted
socket.broadcast.emit("moveAIShipForward", {id: socket.id, i: i})
});
对广播的响应:(SpaceSoccer.java)
.on("moveAIShipForward", new Emitter.Listener() {
...
JSONObject data = (JSONObject) args[0];
try {
// now here, the object looks like above (in the .js file), so `.get("i")` would return a `{ "i": 0 }` obejct, which obviously cannot be converted to int.
int i = data.getInt("i"); // { "i": 0 } is not an integer!
....
});
解决方案(不是唯一的,一旦你知道原因,tho):
在你index.js
改变你要发送的有效负载中,例如:
socket.on("moveAIShipForward", function(data) {
socket.broadcast.emit("moveAIShipForward", {id: socket.id, i: data.i})
});
推荐阅读
- javascript - 通过 hapi/joi 验证对象时在现有错误中添加错误
- reactjs - 如何在页面更改时清除表单错误的 redux 状态
- python - AttributeError:“MLPClassifier”对象没有属性“decision_function”
- python - 为什么当我的播放器向右或向左移动时我的平台在移动
- sql-server - Microsoft SQL 根据其他表组创建汇总表
- javascript - 将 HTML 包含用于站点导航链接
- javascript - JavaScript 将选择从图像复制到图像
- c++ - 警告:在 C++ 中忽略空字符 [-Wnull-character]
- reactjs - TextField Material-ui 无法正常工作 reactjs 和 windows 10
- laravel - 在 Laravel 中集成 Monaco 编辑器以使用它