日期:2014-05-20  浏览次数:20913 次

求助java中Socket问题,急。。。。!
和另一台机子做数据交换。代码如下
Java code
    public String send(String SendMessage,String clientIP,int clientPort) throws UnknownHostException, IOException{
        System.out.println("------------clientIP="+clientIP+"-------------clientPort="+clientPort);
        Socket s = new Socket(clientIP,clientPort);
        System.out.println("s.getOutputStream()"+s.getOutputStream());
        
        PrintStream out = new PrintStream(s.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        InputStream is = s.getInputStream();
        System.out.println("SendMessage:"+SendMessage);
        out.print(SendMessage);

        int b = 0;
        while ((b = is.read()) != -1) {
            System.out.println(b);
            bos.write(b);
            System.out.println(b);
        }
        byte[] bytes = bos.toByteArray();*/
        
        int len = -1;
        while((len=is.available()) <=8) {
            len = is.available();
            System.out.println("len:"+len);
        }
        
        byte[] bytes = new byte[8192];
        is.read(bytes, 0 , bytes.length);
        String ReceiveMessage = StringUtil.trim(new String( bytes));
        
        System.out.println("ReceiveMessage:"+ReceiveMessage);
        out.close();
        s.close();
        is.close();
        return ReceiveMessage;
    }



为什么老是在while((len=is.available()) <=8) {
len = is.available();
System.out.println("len:"+len);
}
中循环,后天总是打印len=0;端口 ip都正确,求解!

------解决方案--------------------
类 InputStream 的 available 方法总是返回 0。

详细api文档。
------解决方案--------------------
api文档是这么写的:
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream。
------解决方案--------------------
返回此输入流方法的下一个调用方可以不受阻塞地从此输入流读取(或跳过)的字节数。