我在服务器输入流扫描器中收到此找不到行的异常

问题描述 投票:0回答:1

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

这里是堆栈跟踪。

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”是套接字输出流。

java java.util.scanner inputstream
1个回答
0
投票

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

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();
    }
}
}
© www.soinside.com 2019 - 2024. All rights reserved.