0

This is my client application that is connected to a server. I use an object called DataPackage to send information back and forth. The code runs in its own thread.

The variable in is an ObjectInputStream and out is an ObjectOutputStream.

DataPackage dp = null;
while (true) {

    try {
        dp = (DataPackage) in.readObject();
        if (dp != null) {
            // Do stuff with received object
        }

        if (sendSomething) { // Send stuff
            out.writeObject( new DataPackage("some data") );
            out.flush();
            out.reset();
        }
    } catch (ClassNotFoundException | IOException e1) {
        e1.printStackTrace();
    }

    try {
        t.sleep(50);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

The problem with my code is that I never reach the part where I send stuff, unless I receive something from the server. The loop waits for something from the server before it continues to if (sendSomething). How should I structure my code so that I can send stuff any time and receive stuff any time? I hope you understand.

4

2 回答 2

2

您可以使用线程。如果它们使用同一个套接字与外部服务器通信,这很常见,因为它们在等待从套接字读取时不会阻塞。

线程1:

在收到消息时阻止阅读 - 做某事

Thread2:对发生的事情做事-写入套接字

于 2013-08-20T11:27:59.320 回答
1

线路dp = (DataPackage) in.readObject();阻塞。这意味着在收到服务器的一些回复之前,它不会完成以下行的执行。

一个建议,创建一个新线程并传递实例, dp = (DataPackage) in.readObject();这样它就不会阻塞。

于 2013-08-20T11:29:15.360 回答