我目前有一个游戏,为此我实现了一个客户端和一个服务器。CPU-Wise,如何优化UDP数据包发送?
我然后让服务器向客户端关于它的位置发送数据,客户端发送移动输入到服务器等
的问题是,在CPU焰火至100%。我已经直接连接在高使用率下面的代码,这是在被每秒称为十倍的更新()方法:
try{
sendToClientUDP(("ID:" + String.valueOf(uid)));
sendToClientUDP(("Scale:" + GameServer.scale));
for (Clients cl : GameServer.players){
//sendToClient(("newShip;ID:" + cl.uid).getBytes(), packet.getAddress(), packet.getPort());
sendToClientUDP((("UID:" + cl.uid +";x:" + cl.x)));
sendToClientUDP((("UID:" + cl.uid +";y:" + cl.y)));
sendToClientUDP((("UID:" + cl.uid +";z:" + cl.z)));
sendToClientUDP((("UID:" + cl.uid +";Rotation:" + (cl.rotation))));
cl.sendToClientUDP(new String("newShip;ID:" + uid));
sendToClientUDP(new String("newShip;ID:" + cl.uid));
}
}catch (Exception e){
e.printStackTrace();
}
卸下代码和CPU使用率过高消失。
这是我的sendToClientUDP()
方法。
public void sendToClientUDP(String str){
if (!NPC){ //NPC is checking if it is a computer-controlled player.
UDP.sendData(str.getBytes(), ip, port);
}
}
这里是我的UDP.sendData()方法:
public static void sendData(String data, InetAddress ip, int port) {
sendData(data.getBytes(), ip, port);
}
public static void sendData(byte[] data, InetAddress ip, int port) {
DatagramPacket packet = new DatagramPacket(data, data.length, ip, port);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
为什么如此多的CPU被简单地通过发送UDP数据包使用?如果有的话,我能做些什么来减少它?
错误,发送所有的东西在一个单一的数据报? – EJP