用udp服务器停止线程

时间:2013-02-11 23:36:52

标签: java multithreading

我有一个实现Runnable接口的UDP服务器类。我在线程中启动它。 问题是我无法阻止它。即使在Debug中,它也会在pt.join()方法停止。

这是我的服务器类

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class Network implements Runnable {
final int port = 6789;

DatagramSocket socket;

byte[] input = new byte[1024];
byte[] output = new byte[1024];

public Network() throws SocketException{
    socket = new DatagramSocket(6789);
}

@Override
public void run() {
    while(true){
        DatagramPacket pack = new DatagramPacket(input,input.length);
        try {
            socket.receive(pack);
        } catch (IOException e) {
            e.printStackTrace();
        }
        input = pack.getData();
        System.out.println(new String(input));
        output = "Server answer".getBytes();
        DatagramPacket sendpack = new DatagramPacket(output,output.length,pack.getAddress(),pack.getPort());
        try {
            socket.send(sendpack);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

这是主要的课程

public class Main {

static Network network = null;

public static void main(String[] args) throws IOException{
    network = new Network();
    System.out.println("Try to start server");
    Thread pt = new Thread(network);
    pt.start();

    pt.interrupt();
    try {
        pt.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("Stop server");
}
}

如何停止服务器?

3 个答案:

答案 0 :(得分:2)

java.net读取是不可中断的。您必须关闭DatagramSocket或将其读取超时(setSoTimeout()),并在得到结果SocketTimeoutException时检查中断状态:如果设置,则退出线程。

答案 1 :(得分:1)

调用interrupt实际上不会停止该线程,它只是设置一个标志。

在循环中,检查isInterrupted()。例如,快速而肮脏的方式将会改变

while(true) 
to 
while (!Thread.currentThread().isInterrupted())

但如果你对这个项目更加认真,你应该查阅更多的文档。

正如@EJP所提到的,如果你挂在Socket IO中,你需要关闭Socket或者超时。

答案 2 :(得分:1)

除了EJP所说的,你可能应该有一个名为running(或者其他)的本地布尔值,并在输入while循环之前将其设置为true。让你的w​​hile循环以这个本地布尔值为条件。并提供方法(stopServer()和isRunning())来设置和检查布尔值的状态。您还可能希望从while循环中删除try-catch并将整个while循环放在try-catch-finally中并在finally语句中执行清理(设置running = false;关闭连接等)< / p>