我正在尝试在连接时从服务器向客户端发送“Hello”...服务器端程序运行正常,但客户端代码出现“数据未准备好读取”的问题
这些是我的代码...请帮助...
服务器端:
import java.net.*;
import java.io.*;
public class ServerSide
{
public static void main(String args[])
{
try
{
ServerSocket ss = new ServerSocket(8888);
System.out.println("Waiting...");
Socket server=ss.accept();
PrintStream ps= new PrintStream(server.getOutputStream());
ps.print("Hello...");
ps.flush();
System.out.println("Data Sent...");
}
catch(Exception e)
{
System.out.println("Error : " + e.toString());
}
}
}
客户端:
import java.net.*;
import java.io.*;
public class ClientSide
{
public static void main(String args[])
{
try
{
String str= new String();
Socket client=new Socket(InetAddress.getLocalHost(),8888);
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
if(br.ready())
{
str=br.readLine();
System.out.println(str);
}
else
{
System.out.println("Data not ready to read from Stream");
}
}
catch(Exception e)
{
System.out.println("Error : " + e.toString());
}
}
}
最佳答案
如果 BufferedReader
在创建后立即没有获取任何数据,那么您当前就会失败。你为什么期望它有?就我个人而言,我很少发现 ready()
和 available()
是有用的方法 - 我建议你只调用 readLine
并阻塞直到出现数据是否可用。
如评论中所述,如果您尝试从客户端读取行,则需要在服务器上写入行 - 因此请考虑使用println
而不是打印
。 (我个人并不是 PrintStream
的粉丝,但那是另一回事。)
关于java - 数据未准备好从流中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18234328/