[英]Client while loop to send and receive from server
This is my client application that is connected to a server. 这是我连接到服务器的客户端应用程序。 I use an object called DataPackage to send information back and forth.
我使用一个称为DataPackage的对象来回发送信息。 The code runs in its own thread.
该代码在其自己的线程中运行。
The variable in
is an ObjectInputStream
and out
is an ObjectOutputStream
. 输入变量
in
是ObjectInputStream
, out
变量是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)
. 循环会等待服务器发出的消息,然后继续执行
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.
我希望你明白。
You can use the threads. 您可以使用线程。 If they use the same socket to communicate with an external server, this is common because they won't block while waiting to read from the socket.
如果他们使用相同的套接字与外部服务器进行通信,这是很常见的,因为它们在等待从套接字读取时不会阻塞。
Thread1: 线程1:
block on read on recieve message - do something 收到邮件时阻止阅读-做某事
Thread2: do things on something happening - write to socket 线程2:对正在发生的事情进行处理-写入套接字
The line dp = (DataPackage) in.readObject();
dp = (DataPackage) in.readObject();
is blocking. 正在阻止。 It means that it will not complete execution of lines below until it receives some reply from server.
这意味着,直到收到服务器的一些答复,它才能完成下面几行的执行。
One advise, create a new thread and pass instance of dp = (DataPackage) in.readObject();
一个建议,创建一个新线程并在
dp = (DataPackage) in.readObject();
传递dp = (DataPackage) in.readObject();
so it won't block. 这样它就不会阻塞
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.