UDP连接不能通过局域网工作

时间:2016-04-23 18:50:10

标签: java networking udp lan

我在项目中设置了客户端和服务器,但他们没有在我的网络上的计算机之间进行连接。

客户:

public class GameClient extends Thread {

private static Image image;

private InetAddress ipAddress;
private DatagramSocket socket;
private Play play;

public GameClient(Play play, String ipAddress){
    this.play = play;

    try {
        this.socket = new DatagramSocket();
        this.ipAddress = InetAddress.getByName(ipAddress);
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

}

public GameClient(Play play, InetAddress ipAddress){
    this.play = play;

    try {
        this.socket = new DatagramSocket();
        this.ipAddress = ipAddress;
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void run() {
    //boolean run = true;
    while(true) {
        byte[] data = new byte[1024];
        DatagramPacket packet = new DatagramPacket(data, data.length);
        try {
            socket.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
    }
}

public static void getImage(Image newImage){
    image = newImage;
}

private void parsePacket(byte[] data, InetAddress address, int port) {
    String message = new String(data).trim();
    PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
    Packet packet = null;
    switch (type) {
    default:
    case INVALID:
        break;
    case LOGIN:
       packet = new Packet00Login(data);
       System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet00Login)packet).getUsername() + " has joined the game");
       PlayerMP player = new PlayerMP(((Packet00Login)packet).getUsername(), (double)200, (double)200, 65, 285, (float)0, (double)1, image, address, port);

       play.addEntity(player);
       play.setClientPlayer(player);
        break;
    case DISCONNECT:
        packet = new Packet01Disconnect(data);
        System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet01Disconnect)packet).getUsername() + " has left the world...");
        play.removePlayerMP(((Packet01Disconnect)packet).getUsername());
        break;
    case MOVE:
        packet = new Packet02Move(data);
        handleMove((Packet02Move) packet);

    }
}

public void sendData(byte[] data){
    DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 1331);
    try {
        socket.send(packet);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void handleMove(Packet02Move packet){
    this.play.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getDirection());
}

}

服务器:

public class GameServer extends Thread {

private static Image image;

private DatagramSocket socket;
private Play play;
private List<PlayerMP> connectedPlayers = new ArrayList<PlayerMP>();

public GameServer(Play play){
    this.play = play;

    try {
        this.socket = new DatagramSocket(1331);
    } catch (SocketException e) {
        e.printStackTrace();
    } 

}

public static void getImage(Image newImage){
    image = newImage;
}

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();
        }
        this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
    }
}

private void parsePacket(byte[] data, InetAddress address, int port) {
    String message = new String(data).trim();
    PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
    Packet packet = null;
    switch (type) {
    default:
    case INVALID:
        break;
    case LOGIN:
        packet = new Packet00Login(data);
        System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet00Login)packet).getUsername() + " has connected to the server...");
        PlayerMP player = new PlayerMP(((Packet00Login)packet).getUsername(), (double)200, (double)200, 65, 285, (float)0, (double)1, image, address, port);
        this.addConnection(player, (Packet00Login)packet);

        break;
    case DISCONNECT:
        packet = new Packet01Disconnect(data);
        System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet01Disconnect)packet).getUsername() + " has left...");
        this.removeConnection((Packet01Disconnect)packet);
        break;
    case MOVE:
        packet = new Packet02Move(data);
        //System.out.println(((Packet02Move)packet).getUsername() + " has moved to " + (int)((Packet02Move)packet).getX() + " , " + (int)((Packet02Move)packet).getY());
        this.handleMove(((Packet02Move)packet));
        break;
    }
}

public void addConnection(PlayerMP player, Packet00Login packet) {
    boolean alreadyConnected = false;
    if(!this.connectedPlayers.isEmpty()){
        for(PlayerMP p: this.connectedPlayers){
            if(player.getUsername().equalsIgnoreCase(p.getUsername())){
                System.out.println("Client " + player.getUsername() + " already conected as " + p.getUsername() + ": updating player information");
                if(p.getIpAddress() == null){
                    p.setIpAddress(player.getIpAddress());
                }
                if(p.getPort() == -1){
                    p.setPort(player.getPort());
                }
                alreadyConnected = true;
            }else{
                // relay to the current connected player that there is a new
                // player
                sendData(packet.getData(), p.getIpAddress(), p.getPort());

                // relay to the new player that the currently connect player
                // exists

                packet = new Packet00Login(p.getUsername());
                System.out.println("Sending already conected player to [" + player.getIpAddress().getHostAddress() + ":" + player.getPort() + "] " + player.getUsername());
                sendData(packet.getData(), player.getIpAddress(), player.getPort());
            }
        }
    }else{
        System.out.println("Sending login to [" + player.getIpAddress().getHostAddress() + ":" + player.getPort() + "] " + player.getUsername());
        sendData(packet.getData(), player.getIpAddress(), player.getPort());
        this.connectedPlayers.add(player);
        alreadyConnected = true;
    }
    if(!alreadyConnected){
        System.out.println("Sending login to [" + player.getIpAddress().getHostAddress() + ":" + player.getPort() + "] " + player.getUsername());
        packet = new Packet00Login(player.getUsername());
        sendData(packet.getData(), player.getIpAddress(), player.getPort());
        this.connectedPlayers.add(player);

    }
}


public void removeConnection(Packet01Disconnect packet) {
    this.connectedPlayers.remove(getPlayerMPIndex(packet.getUsername()));
    packet.writeData(this);
}

public PlayerMP getPlayerMP(String username){
    for(PlayerMP player : this.connectedPlayers){
        return player;
    }
    return null;
}

public int getPlayerMPIndex(String username){
    int index = 0;
    for(PlayerMP player : this.connectedPlayers){
        if(player.getUsername().equals(username)){
            break;
        }
        index++;
    }
    return index;
}

public void sendData(byte[] data, InetAddress ipAddress, int port) {
    DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
    try {
        this.socket.send(packet);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void sendDataToAllClients(byte[] data) {
    for (PlayerMP p : connectedPlayers) {
        sendData(data, p.getIpAddress(), p.getPort());
    }
}

private void handleMove(Packet02Move packet){
    if(getPlayerMP(packet.getUsername()) != null){
        int index = getPlayerMPIndex(packet.getUsername());
        this.connectedPlayers.get(index).x = packet.getX();
        this.connectedPlayers.get(index).y = packet.getY();
        ((PlayerMP)this.connectedPlayers.get(index)).playerDirection = packet.getDirection();
        packet.writeData(this);
    }
}

}

这里是从我的play类向服务器发送第一个登录数据包的地方(此数据包未被接收)

    if(JOptionPane.showConfirmDialog(null, this, "do you want to start the server?", mousePosX) == 0){
        socketServer = new GameServer(this);
        socketServer.start();
    }
    try {
        socketClient = new GameClient(this, InetAddress.getLocalHost());
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    socketClient.start();
    GameClient.getImage(standing);// these are just so that the client and the server have the image to create the player entity once they join the game

    GameServer.getImage(standing);
    Packet00Login loginPacket = new Packet00Login(Global.playerUsername);
    loginPacket.writeData(socketClient); //this is where the first login is being sent, it is not being received.

要清楚程序在一台计算机上运行并且ip看起来正确(192.0.0.XXX)但是当我选择在一台计算机上运行服务器而不在另一台计算机上运行服务器时第二台计算机没有连接到第一个。

提前感谢!

1 个答案:

答案 0 :(得分:0)

想出来,无论做什么都要做网络工作:P结果我意外地直接调用服务器来发送信息而不是客户端。将服务器移动到一个新项目,并将其设置为独立,因为我应该首先完成,一切都很好:)。谢谢你的帮助!