[英]Java network transfer large amount data
i am recently working on multiplayer client/server typing game for 3 players. 我最近正在为3个玩家开发多人客户端/服务器打字游戏。 Now i am sending
3xboolean
, double
, 2xint
and long
. 现在我要发送
3xboolean
, double
, 2xint
和long
。 I want to ask if is possible to somehow pack the data and send just the data packet. 我想问一下是否可以打包数据并仅发送数据包。
Instead of writing the actual object to the network I would recomend serializing it to a stable format (JSON for example) and sending that. 我不建议将实际对象写入网络,而是建议将其序列化为稳定的格式(例如JSON)并发送。 The receiving end would get the JSON from the socket and decode to an object.
接收端将从套接字获取JSON并解码为一个对象。 Here is a quick example of what you need (I used GSON for Json parsing)
这是您需要的一个简单示例(我使用GSON进行Json解析)
public static void main(String[] args) {
Gson gson = new Gson();
//Sender side
Message message = new Message();
message.setA(true);
message.setD("Hello World");
String messageAsJson = gson.toJson(message);
//write messageAsJson to socket
System.out.println(messageAsJson);
//Receiver side, reads line from socket and decodes
Message decodedMessage = gson.fromJson(messageAsJson, Message.class);
System.out.println(decodedMessage.getA());
System.out.println(decodedMessage.getD());
}
public static class Message {
private Boolean a;
private String d;
public Boolean getA() {
return a;
}
public void setA(Boolean a) {
this.a = a;
}
public String getD() {
return d;
}
public void setD(String d) {
this.d = d;
}
}
Checkout this example. 看看这个例子。 You have to create a Class with following fields
您必须使用以下字段创建一个类
3xboolean, double, 2xint and long
3xboolean,double,2xint和long
and use transport approach provided here --> http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html 并使用此处提供的传输方法-> http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.