本帖最后由 康乐 于 2012-12-23 20:42 编辑
- import java.io.*;
- import java.net.*;
- class TcpClient2
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket(InetAddress.getLocalHost(),10002);
- OutputStream out = s.getOutputStream();
- out.write("请求数据".getBytes());
-
- InputStream in = s.getInputStream();
- byte[] buf = new byte[1024];
- int len = 0;
- while((len = in.read(buf))!=-1)
- {
- System.out.println(new String(buf,0,len));
- }
- s.close();
- }
- }
- class TcpServer2
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(10002);
- Socket s = ss.accept();
- String ip = s.getInetAddress().getHostAddress();
- System.out.println(ip+"connect");
- InputStream in = s.getInputStream();
- byte[] buf = new byte[1024];
-
- int len = in.read(buf);
- System.out.println(new String(buf,0,len));
-
- /*为什么这样写会阻塞?
-
- int len = 0;
- while((len = in.read(buf))!= -1)
- {
- System.out.println(len+new String(buf,0,len));
- }
- */
-
- OutputStream out = s.getOutputStream();
- out.write("收到请求,已处理".getBytes());
- s.close();
- ss.close();
- }
- }
复制代码 代码如上,为什么在服务端读取Socket中的InputStream时,用while时,程序会阻塞?
int len = in.read(buf);
System.out.println(new String(buf,0,len));语句后面再加一句System.out.println(in.read(buf))也会阻塞。
为什么呢?
int len = 0;
while((len = in.available())>0)
{
in.read(buf);
int count = len<buf.length?len:buf.length;
System.out.print(new String(buf,0,count));
}
这样能解决问题,可是,为什么呢
|