java套接字数据处理

java socket data processing

我目前正在开发一个 java 从互联网设备获取数据的程序。

连接和初始化过程已经按预期工作,但是当我想处理收到的数据时,发生了一些奇怪的事情...

Exception in thread "main" java.lang.NullPointerException

当我想打印接收到的套接字信息时,以下代码会出现此错误:

static String tempstring;
        while((tempstring = reader.readLine()) != null){
            System.out.println("Client: " + tempstring);
        }

        System.out.print(tempstring);

事实是,在 while 循环中数据被正确接收。但在那之后,在最后一行打印功能中,数据不再可用。有谁知道我做错了什么?

您似乎在尝试打印空值,因为您为每次迭代分配了从 reader 读取的一行,因此在退出 while 循环时得到空值。您需要连接您阅读的每一行以便以后使用它。 这样的事情会起作用:

String tempstring;  
String readerData = "";  
while((tempstring = reader.readLine()) != null){
        readerData += tempstring;
        System.out.println("Client: " + tempstring);
}
System.out.print(readerData);