如何以正确的顺序生成自动化的客户端 – 服务器Java网络代码输出?
首先让我说我知道这是很多代码,所以请耐心等待。 我正在开发一个项目,我正在将Oracle的Knock-Knock客户端/服务器示例移植到美国的State-Capital示例中。 因此,它不是KnockKnock笑话,而是运行一系列州资本查询。 它的运行大致如下:
服务器:我可以向您发送州资本查询吗?
客户:好的
服务器:发给我一个州,所以我可以寄一个资金?
客户:阿拉巴马州
服务器:阿拉巴马州的首府是亨斯特维尔。 想要另一个(是/否)?
客户:n
执行此项目的动机是稍后演示某种类型的故障安全function(在我开始工作之后,我想使用Powershell并使用它来将客户端 – 服务器作为一个单元运行)。
回到我的代码。 当我运行它时,它给了我以下输出,这不是我正在寻找的。 它应该是同步的,以便客户端和服务器一次处理一个状态。 相反,客户端跳过服务器端,并没有到达怀俄明州的最后状态。 我尝试根据这个问题添加一些同步。
我已经在pastebin上链接了完整的代码
FixedMessageSequenceClient
FixedMessageSequenceServer
FixedMessageSequenceProtocol
在代码中,我使用整数的简单文本日志文件:
1 2 3 4
注意:我正在使用Apache ReversedLinesFileReader库。
我怀疑我的错误是因为Java IO写入花费的时间太长。 我想可能是因为这段代码:
for (int i = modlastNum; i < KKJokes.length ; i++){ String fromServer = br.readLine(); out.println(KKJokes[ i % KKJokes.length ]); if ( (i % 3 )==2){ try { Thread.sleep(11); } catch (InterruptedException ie) {} } // fromServer = br.readLine(); System.out.println ( fromServer ); fromServer = br.readLine(); System.out.println ( fromServer ); // String fromServer3 = br.readLine(); System.out.println ( fromServer3 ) ; System.out.println ( fromServer ) ; if(fromServer.equals("inputOfYes")){ while (!(fromServer.equals("nowlogged"))) { fromServer = br.readLine(); } } System.out.println ( fromServer ) ; } // end-forLoop starting at Ln. 93
所以我的预感是我自动向FixedMessageSequenceServer
类发送查询(通过FixedMessageSequenceProtocol
类)可能过快,而且FixedMessageSequenceClient
的IO可能是瓶颈。
任何关于如何调试或弄清楚的提示都表示赞赏,谢谢
不需要新的答案。 感谢上面的Paul,鼓励我自己解决这个问题:
问题是,我忽略了FixedSequenceMessageProtocol
类的重要性
由于客户端是硬编码的,以便在大型StateResponses
数组中发送所有内容,因此需要为“ack”(理想情况下应该是多维数组)提供第四个字段,该字段与服务器发送的“nowlogged”配对:
StateResponses[] = { "Permission granted." , "What is Alabama population", "y", "ack", //00 "Permission granted." , "What is Alaska population", "y", "ack",
在此之后,在FixedSequenceMessageProtocol
类中,我添加了一个新的常量final变量,以在我们记录状态位置后指示pending-status, SENTPERMISSION2
:
private static final int WAITING = 0; private static final int SENTPERMISSION = 1; private static final int SENTPERMISSION2 = 2; // ** new line private static final int SENTCLUE = 3; private static final int ANOTHER = 4;
下面,我只需要在FixedSequenceMessageProtocol
类的nested-if块中添加另一个案例:
/* etc more code */ { if (theInput.equalsIgnoreCase(clues[currentPopulationRequest])) { theOutput = answers[currentPopulationRequest] + " Want another? (y/n)"; currentPopulationRequest++; state = SENTPERMISSION2 ; //sentpermssion2, & in sentPermission2 put another } else { theOutput = "You're supposed to say \"" + clues[currentPopulationRequest] + "! Try again. Request to send a state population"; state = SENTPERMISSION; } } else if (state == SENTPERMISSION2) { if (theInput.equalsIgnoreCase("y")) { theOutput = "Status logged"; state = ANOTHER; } else { theOutput = "Bye."; state = WAITING; } } else if (state == ANOTHER) { if (theInput.equalsIgnoreCase("ack")) { /* etc more code */