java - 如何使用线程调用另一个类的不同函数

标签 java multithreading junit

我有一个服务器类,它具有三种方法启动/停止/重定向。请找到下面的代码。

public class Syslog
{
private static final int PORT = 519;
private static final int BUFFER_SIZE = 10000;
private static boolean server_status=false;


public static void startServer()
{
server_status=true;
}

public static void stopServer()
{
server_status=false;
}

public void redirectToFile(byte[] bs) throws IOException
{
String data=new String(bs);

File file = new File("C:\\audit_log.txt");

// if file doesn't exists, then create it
if (!file.exists()) {
    file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();

System.out.println("Done");

}

public void runServer() throws IOException
{
DatagramSocket socket = new DatagramSocket(PORT);
DatagramPacket packet = new DatagramPacket(new      byte[BUFFER_SIZE],BUFFER_SIZE);

System.out.println("Receiving data from the socket and redirecting it to a  file C:\\audit_log.txt");
while(server_status)
{
packet.setLength(BUFFER_SIZE);
socket.receive(packet);

System.out.printf("Got %d bytes from  %s%n",packet.getLength(),packet.getSocketAddress());
System.out.write(packet.getData());

redirectToFile(packet.getData());
}

socket.close();
}

}

我有一个 junit 测试,我想在 @beforeclass 中启动服务器并在 @afterclass 中停止它。我还需要在测试执行期间调用 runServer() 。我尝试使用线程,但在实现过程中感到非常困惑。有人可以指出一种设计方法来处理这个问题吗?然后我会尝试相应地编码。

最佳答案

建议您在 runServer() 中生成一个线程。这样您就不必在 JUnit 测试中处理线程。像这样的事情:

private Thread serverThread;
IOException thrown;

public void runServer() throws IOException {
    if (serverThread != null) {
        throw new IOException("Server is already running");
    }
    serverThread = new Thread(new Runnable() {
        public void run() {
            DatagramSocket socket = null;
            try {
                socket = new DatagramSocket(PORT);
                DatagramPacket packet = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
                while (server_status) {
                    packet.setLength(BUFFER_SIZE);
                    socket.receive(packet);
                    System.out.write(packet.getData());
                    redirectToFile(packet.getData());
                }
            } catch (IOException e) {
                thrown = e;
            } finally {
                serverThread = null;
                if (socket != null) socket.close();
            }
        }
    });
    serverThread.start();
}

关于java - 如何使用线程调用另一个类的不同函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978056/

相关文章:

java - 我的java(生产者-消费者)代码有什么问题?

java - 在 Camel 中模拟文件端点

Java 异步处理

java - 如何读取包含文本和整数的文件并将整数保存在数组列表中

java - 跟踪执行线程

java - 虽然 Android 中真正的 bucles

java - 如何对调用 void 方法的方法进行单元测试?

java - 如何确保我的 arrayList 中嵌套私有(private)类的对象是我想要的?

java - 从自定义 LinkedList 数组的 addToBack 方法引发 NullPointerException

java - 如何使用内联匿名类声明避免合成访问编译器警告,这是什么意思?