数据尚未准备好从Stream读取

时间:2013-08-14 14:20:46

标签: java sockets

我正在尝试从服务器向客户端发送“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());
       }
}

}

2 个答案:

答案 0 :(得分:4)

如果BufferedReader在创建后没有立即获取任何数据,那么您目前失败了。你为什么期望它有?就个人而言,我很少发现ready()available()是有用的方法 - 我建议您只需调用readLine并阻止,直到 数据可用。

如评论中所述,如果您尝试从客户端读取行,则需要在服务器上行 - 因此请考虑使用{{1}而不是println。 (我个人不是print的粉丝,但这是另一回事。)

答案 1 :(得分:0)

使用

String in = null;
while ((in = br.readLine()) != null) {
    // This will loop until EOF and in will hold the last read line
}