在 java 中收到响应之前如何停止方法?
How to stop a method until I get the response in java?
我编写了一个简单的 TCP 服务器程序,用于从客户端接收数据。我的 main() 方法如下所示:
Acceptor acceptor = Acceptor.open(new InetSocketAddress(port));
Session session = acceptor.accept(); //accepts connection from client and returns session object
FIXSession transport = session.getTransport();
String str = transport.receive(); // receives data from client
doWork(str); // do the remaining process.
在上面的代码中,我尝试使用 "transport.receive()" 方法从客户端接收数据。如果假设客户端需要一些时间来发送数据,同时我的主程序将进入下一步"doWork(str);",结果为空。我怎样才能让 main() 线程等待,直到我从客户端接收到数据。将来我可能 运行 其他线程中的 doWork(str) 方法。所以我需要让 doWork(str) 线程等待,直到我从客户端获取数据。有什么办法吗?
引用OP:
Even though it returns the number of bytes, if the bytes received less than 0 then it has to wait until the received bytes are greater than 0
因此,将其转变为阻塞调用的直接方法是:
int numBytes = transport.receive();
while (numBytes == 0) {
Thread.sleep(SOME_TIME);
numBytes = transport.receive();
}
例如。如果你想让代码等待;然后编写等待的代码。但是,当然,这仍然没有回答如何实际上 接收消息。因为这个想法是你需要 MessageListener
来实际接收消息。
我编写了一个简单的 TCP 服务器程序,用于从客户端接收数据。我的 main() 方法如下所示:
Acceptor acceptor = Acceptor.open(new InetSocketAddress(port));
Session session = acceptor.accept(); //accepts connection from client and returns session object
FIXSession transport = session.getTransport();
String str = transport.receive(); // receives data from client
doWork(str); // do the remaining process.
在上面的代码中,我尝试使用 "transport.receive()" 方法从客户端接收数据。如果假设客户端需要一些时间来发送数据,同时我的主程序将进入下一步"doWork(str);",结果为空。我怎样才能让 main() 线程等待,直到我从客户端接收到数据。将来我可能 运行 其他线程中的 doWork(str) 方法。所以我需要让 doWork(str) 线程等待,直到我从客户端获取数据。有什么办法吗?
引用OP:
Even though it returns the number of bytes, if the bytes received less than 0 then it has to wait until the received bytes are greater than 0
因此,将其转变为阻塞调用的直接方法是:
int numBytes = transport.receive();
while (numBytes == 0) {
Thread.sleep(SOME_TIME);
numBytes = transport.receive();
}
例如。如果你想让代码等待;然后编写等待的代码。但是,当然,这仍然没有回答如何实际上 接收消息。因为这个想法是你需要 MessageListener
来实际接收消息。