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

socket接收报错,求指导
/**
 * 报文头固定5位为报文长度,按长度接收
 * @param socket 
 * @return 接收到的报文
 */
public static byte[] accept(Socket socket){
byte [] head = new byte[5];  
        byte [] body=null;  
        try {  
            BufferedInputStream bufIn = new BufferedInputStream(socket.getInputStream());  
            bufIn.read(head); 
            System.out.println("head "+new String(head));
            int len1 = Integer.parseInt(new String(head));  
            body = new byte[len1];  
            bufIn.read(body);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          return body;  
}

客户端接收调用:
 byte[] res = SocketUtil.accept(socket);//读取服务器端返回bytes
String str=new String(res);//转化为String
str=ByteOrStringHelper.ByteToString(res,"GBK");//根据编码格式转化
System.out.println("读取服务器返回数据:"+str);

一接收就报错java.lang.NumberFormatException: For input string: "    h"
搞不懂哪错了.接收报文不能2次接收数据吗?不能根据报文长度接收具体长度报文吗?还是其他地方错误.求指导!

------解决方案--------------------
客户端度到的是字符串,字符串转换出错了,不能讲 “ h”转换为Int。
int len1 = Integer.parseInt(new String(head));