致力于小型视频游戏多人游戏。第一个玩家是服务器,第二个是客户端。我在客户端和服务器上都有2个方法networkSend()和networkRecive()。如果我只使用服务器networkReceive()和客户端networkSend(),我可以看到我的船只移动。但是如果我在服务器和客户端都使用它们,那么我就无法移动任何船只。看起来像networkRecieve()等待响应我猜。如何使它们兼具?
第一个玩家和第二个玩家包含几乎相同的代码
// network variables
String ip;
InetAddress address = null;
byte[] buf = new byte[256];
int port = 5001;
DatagramSocket socket = null;
DatagramPacket packet = null;
public Board() {
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
craft = new Craft();
enemy = new Enemy();
timer = new Timer(5, this);
timer.start();
// DatagramSocket socketS;
try {
socket = new DatagramSocket(5001);
System.out.println("Socket created on "+ port + " port");
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Starting server...");
}
public void actionPerformed(ActionEvent e) {
craft.move();
// enemy.move();
networkReceive();
// if networkSend() is commented than it works
networkSend();
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
craft.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
craft.keyPressed(e);
}
}
public void networkSend(){
// Serialize to a byte array
try {
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutputStream oo;
oo = new ObjectOutputStream(bStream);
oo.writeObject(craft);
oo.flush();
oo.close();
byte[] bufCar = bStream.toByteArray();
DatagramPacket packet = new DatagramPacket(bufCar, bufCar.length, address, port);
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void networkReceive() {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
System.out.println("Printing buf="+buf+" and socket "+socket);
socket.receive(packet);
byte[] data = packet.getData();
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
enemy = (Enemy) is.readObject();
System.out.println("Enemy x="+enemy.getX()+" and y="+enemy.getY());
address = InetAddress.getLocalHost();
port = packet.getPort();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}