请教JAVA网络编程中read阻塞的问题

J2EE 码拜 7年前 (2017-05-05) 1716次浏览
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9080);// 指定在服务器机子上的端口号
Socket s = ss.accept();
InputStream ins = s.getInputStream();
System.out.println(s.getInetAddress().getHostAddress()+ “…..Conection”);
byte[] buf = new byte[1204];
int len = 0;
// while ((len = ins.read(buf)) != -1) {
// System.out.println(new String(buf, 0, len));}

len = ins.read(buf);
System.out.println(new String(buf,0,len));

System.out.println(“11111”);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(“<font color=”red” size=”7″>欢迎光临</font>”);
s.close();
ss.close();
}
请教高手,在上模拟tomcat服务器代码中,为什么红色的部分会阻塞,而蓝色的部分就不会?
解决方案

10

不是一回事吧.. while那不是循环吗.

3

dubug调试一下,看每次循环 ins.read(buf)) 读到的数据详情,观察是什么引起了阻塞

15

网络编程,都是阻塞的io,原因是他一直在等待结果,假如没有结果就会一直等待。假如不想这样,就需要用多线程来写这个例子

12

你这是在阻塞IO,IO资源主线程不能死锁,不能等到读完给String,而是要起另外的IO线程来处理。可参考同步编程

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明请教JAVA网络编程中read阻塞的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)