gpt4 book ai didi

java - 在套接字上设置超时时出现 NoSuchElementException

转载 作者:行者123 更新时间:2023-12-02 08:17:56 27 4
gpt4 key购买 nike

我想在客户端读取时设置超时。该例程应该抛出 InterruptedIOException,但它在 System.out.println("echo: " + _in.nextLine()); 上抛出 NoSuchElementException我做错了什么?

这是我的方法

public void startUserInput()
{
try {
_out = new PrintWriter(_echoSocket.getOutputStream(), true);
_in = new Scanner(new InputStreamReader(_echoSocket.getInputStream()));

Scanner stdIn = new Scanner(new InputStreamReader(System.in));
System.out.print("Input: ");
while (stdIn.hasNextLine()) {
_out.println(stdIn.nextLine());
System.out.println("echo: " + _in.nextLine());
System.out.print("Input: ");
}
stdIn.close();

}catch (InterruptedIOException exception){
System.err.println("The server is not responding " + _serverHostname);

}
catch (IOException e) {
System.out.println("error" + e.getLocalizedMessage());
}}

这是我的连接

public boolean establishConnection()
{
System.out.println ("Connecting to the host " +
this.getServerHostname() + " au port " + this.getServerPort());

try {
_echoSocket = new Socket();
_echoSocket = new Socket(this.getServerHostname(), this.getServerPort());
_echoSocket.setSoTimeout(10000);
System.out.println(_echoSocket.getOutputStream());
return _echoSocket.isConnected();

} catch (UnknownHostException e) {
System.err.println("Unknown host: " + this.getServerHostname());
return false;



} catch (IOException e) {
System.err.println("Error while connecting to the server : " +
this.getServerHostname() + ":" + this.getServerPort());
return false;
}
}

谢谢

最佳答案

原因是当您调用 _in.nextLine() 时,没有从 Scanner 对象 _in 中读取任何行。

您在 while 循环中所做的是检查 stdIn.hasNextLine() 但您没有检查 _in 是否具有可以读取的 nextLine() 。

有关异常的详细信息,您可以查看:

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html#nextLine()

希望有帮助:)干杯!

关于java - 在套接字上设置超时时出现 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5986394/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com