如果在socket中有下面这种情况发生,就不能使用,一般的方法读取socket中的字节
Socket socket=new Socket(ip,port);
socket.setSendBufferSize(1);
socket.getOutputStream().write("nihaoddddddddddddddd".getBytes());
socket.getOutputStream().flush();
socket.getOutputStream().write("dajiahao".getBytes());
socket.getOutputStream().flush();
socket.getOutputStream().write("222".getBytes());
socket.getOutputStream().flush();
socket.getOutputStream().close();
可以使用下面的方法读取
public static byte[] readSocket(Socket socket) throws Exception{
ArrayList l=new ArrayList();
InputStream out=socket.getInputStream();
int totallen=0;
int count;
/**
* 如果socket对方已经将socket关闭,再次读socket里面的内容放回count为负数;
* 读socket超时,反回已经读的字节
*/
for(;;){
byte[] tmp=new byte[3000];
try{
//System.err.println(out.available());
count=out.read(tmp);
System.err.println("count"+count);
}catch(Throwable e){
e.printStackTrace();
System.err.println("ddddddddddddd");
break;
}
System.err.println("count"+count);
if(count<=0){
break;
}
totallen+=count;
byte[] tmp2=new byte[count] ;
System.arraycopy(tmp,0,tmp2,0,count);
l.add(tmp2);
}
byte[] bs=new byte[totallen];
int pos=0;
for(int i=0;i<l.size();i++){
byte[] tmp=(byte[])l.get(i);
System.arraycopy(tmp,0,bs,pos,tmp.length);
pos+=tmp.length;
}
return bs;
}
本文地址:http://com.8s8s.com/it/it11021.htm