gpt4 book ai didi

java - 我在服务器输入流扫描仪中收到此 no line found 异常

转载 作者:行者123 更新时间:2023-12-01 20:10:50 25 4
gpt4 key购买 nike

我正在构建一个小型服务器客户端程序,我正在使用扫描仪来扫描输入流。但每次都没有发现线路异常。我不知道该怎么办。请帮助...有一行服务器的输出流正在传递给客户端。

这是堆栈跟踪。

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Client.main(Client.java:26)

这是一个代码..

public class Client
{
public static void main(String[] args) throws IOException
{
final int SBAP_PORT = 100;
try (Socket s = new Socket("localhost", SBAP_PORT))
{
InputStream instream = s.getInputStream();
OutputStream outstream = s.getOutputStream();
Scanner in = new Scanner(instream);
PrintWriter out = new PrintWriter(outstream);

Scanner scanner = new Scanner(System.in);
String command = scanner.nextLine(); // client interact with server through here.

while(!command.equalsIgnoreCase("QUIT")) {
out.print(command+"\n");
out.flush();
String response = in.nextLine(); // i am getting error here.
System.out.println(response);
command = scanner.nextLine();
}
command = "QUIT";
System.out.println(command);
out.print(command);
out.flush();
}
}
}

这就是服务器向客户端发送响应的方式。

if(command.equalsIgnoreCase("track"))
{
data = new ServerData(phrase);
Thread t = new Thread(data);
t.start();
usr.addPortfolio(data.getTicker(), data.getPrice());
out.print("OK!");
out.flush();
}

“out”是套接字输出流。

最佳答案

这可能是因为服务器响应没有任何换行符。我将重写处理从套接字返回的数据的方式,只需逐字节读取数据即可。

public class Client
{
public static void main(String[] args) throws IOException
{
final int SBAP_PORT = 8080;
try (Socket s = new Socket("localhost", SBAP_PORT))
{
InputStream instream = s.getInputStream();
OutputStream outstream = s.getOutputStream();

//Scanner in = new Scanner(instream);
PrintWriter out = new PrintWriter(outstream);

Scanner scanner = new Scanner(System.in);
String command = scanner.nextLine();
System.out.println("Command: " + command);


while(!command.equalsIgnoreCase("QUIT")) {
out.print(command+"\n");
out.flush();
//String response = in.nextLine(); // i am getting error here.
int i = 0;
char c;
while(( i = instream.read())!=-1) {

// converts integer to character
c = (char)i;

// prints character
System.out.print(c);
}



command = scanner.nextLine();
}
command = "QUIT";
System.out.println(command);
out.print(command);
out.flush();
}
}
}

关于java - 我在服务器输入流扫描仪中收到此 no line found 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58966694/

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