我正在尝试组装一个坦克游戏,我遇到了网络部分的问题。我在服务器上做错了什么?
这是我的服务器代码:
import java.io.*;
import java.net.*;
class UDPServer extends Thread{
private DatagramSocket socket;
private TanksComponent tank;
private InetAddress IPAddress;
private int port = 9876;
public void UPDServer() throws IOException{
socket = new DatagramSocket(port);
}
public void run(){
while(true){
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("RECEIVED: " + packet.getAddress() + " " + packet.getPort() + ": " + new String(packet.getData()) ) ;
IPAddress = packet.getAddress();
}
}
public void sendData(byte[] data){
DatagramPacket packet = new DatagramPacket(data, data.length, IPAddress, port);
try {
this.socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是我的客户代码:
import java.io.*;
import java.net.*;
class UDPClient extends Thread{
private InetAddress ipAddress;
private DatagramSocket clientSocket;
private TanksComponent tank;
private byte[] data = new byte[1024];
private int port = 9876;
public UDPClient(TanksComponent tanksComponent) throws SocketException, UnknownHostException{
this.tank = tanksComponent;
this.clientSocket = new DatagramSocket();
this.ipAddress = InetAddress.getLocalHost();
}
public void run(){
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
clientSocket.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String message = new String(packet.getData());
System.out.println("SERVER > " + message);
}
public void sendData(byte[] data){
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
try {
clientSocket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我正在调用这样的代码:
public void start() throws UnknownHostException, SocketException {
if(JOptionPane.showConfirmDialog(this, "Server") == 0){
socketServer = new UDPServer();
socketServer.start();
}else{
socketClient = new UDPClient(this);
socketClient.start();
System.out.println("Send");
socketClient.sendData("ping".getBytes());
}
感谢陌生人的帮助!