为什么is.avaliable()返回是0,而有的时候是成功的。
客户端发送一字符串给服务端,服务端输入流调用avaliable()方法返回是0;
同样,服务端返回信息给客户端,客户端输入流调用avaliable()方法返回是0;
服务端
package com.longqihai.server;
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket;
public class Server { public static void main(String[] args) { ServerSocket acceptScoket = null; try { acceptScoket = new ServerSocket(9999); Socket socket = acceptScoket.accept(); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); byte[] b = new byte[is.available()]; while(is.available()>0){ is.read(b); } System.out.println("客户端:"+new String(b)); os.write(new String("你好我收到了").getBytes()); os.flush(); System.out.println("执行完成了"); is.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
客户端:
package com.longqihai.client2;
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException;
public class Client { public static void main(String[] args) throws UnknownHostException, IOException { Socket socket = new Socket("127.0.0.1",9999); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); os.write(new String("我来看你了").getBytes()); os.flush(); byte[] b = new byte[1024]; if(is.available()>0) is.read(b); System.out.println("12:"+new String(b)); is.close(); os.close(); socket.close(); } }