我第一次尝试为 php 套接字服务器编写客户端,但遇到了一些麻烦,而且信息淹没了我!
对于服务器,我们需要一个打开的连接,我希望我的客户端等待,直到收到数据,然后再通知线程开始解析输入流。这可以在不使用循环的情况下实现吗?我宁愿能够调用 lock.notify()。
我也在关注 NIO,这是我想要的可行选择吗? 这是我到目前为止的代码,但同样,我只是想避免使用 for(;;),甚至可能对收到的消息进行排队,因为它们很可能只是 JSON
Thread serverRecieve = new Thread(new Runnable() {
@Override
public void run() {
try {
for (;;) {
if (in != null) {
String line;
while ((line = in.readLine()) != null) {
sout(line);
}
} else {
sout("inputstream is null! Waiting for a second to test again");
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(WebManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (IOException ex) {
Logger.getLogger(WebManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
谢谢大家! PS:我确实浏览了这里的很多套接字线程,但认为询问我需要什么会更容易。
最佳答案
我认为您可以使用 while
循环并使用 in != null
放置一个条件:
while(in == null){
//wait for a second before checking the in stream again
try {
sout("inputstream is null! Waiting for a second to test again");
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(WebManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
//now your in is available. Read the data and proceed
String line = null;
while ((line = in.readLine()) != null) {
sout(line);
}
一旦 in
流可用,第一个 while
循环就会终止。
关于Java:同步套接字输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13592783/