public class TestServer { public static void main(String...args){
try{
ServerSocket ss = new ServerSocket(8888);
Socket s = null;
while(true){
s = ss.accept();
OutputStream os = s.getOutputStream();
os.write(TestServer.class.getName().getBytes());
os.close();
s.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}//////////////////////////////////////public class TestClient { public static void main(String[] args) {
Socket s = null;
while(true){
try{
s = new Socket("127.0.0.1",8888);
InputStream is = s.getInputStream();
byte[] buff = new byte[is.available()];
System.out.println(is.available());
is.read(buff,0,buff.length);
System.out.println(new String(buff));
is.close();
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
}}为什么客户端会的is.available()有很多是0的情况? 难道是丢包吗?
throws IOException返回此输入流方法的下一个调用方可以不受阻塞地从此输入流读取(或跳过)的字节数。下一个调用方可能是同一个线程,也可能是另一个线程。
类 InputStream 的 available 方法总是返回 0。 此方法应该由子类重写。
返回:
可以不受阻塞地从此输入流读取的字节数。
抛出:
IOException - 如果发生 I/O 错误。
为使解析数据简单化,可以用ObjectInputStream