user1650305
user1650305

Reputation:

Why does this thread only run once?

I have a server running on a separate thread, and for some reason, it only runs when it receives packets! Why is it doing this? Shouldn't it be running continuously?

public void run() {
    while (running) {
        System.out.println(true);
        byte[] data = new byte[1024];
        DatagramPacket packet = new DatagramPacket(data, data.length);
        try {
            this.socket.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
    }
}

And I start it like this:

public static void main(String[] args) {
    GameServer server = new GameServer();
    server.start();
}

The class extends Thread.

Upvotes: 0

Views: 100

Answers (3)

Peter Walser
Peter Walser

Reputation: 15706

Your Thread is running correctly. The method DatagramSocket.receive(DatagramPacket) blocks until a packet is received.

The default behaviour is to block infinitely until a packet is received. You can specfiy a timeout using DatagramSocket.setSoTimeout(int), if you want to periodically log whether a packet is received or not, or to check if your Thread is still running.

Upvotes: 3

Prettygeek
Prettygeek

Reputation: 2531

From here

public void receive(DatagramPacket p)
             throws IOException

Receives a datagram packet from this socket. When this method returns, the DatagramPacket's buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine.

This method blocks until a datagram is received. The length field of the datagram packet object contains the length of the received message. If the message is longer than the packet's length, the message is truncated.

It clearly says that method blocks and wait for Datagram.

Upvotes: 3

stinepike
stinepike

Reputation: 54682

socket.receive is a blocking method. So the code is waiting on receive untill you receive any data.

Upvotes: 6

Related Questions