请教关于Socket的close()会阻塞的问题。
最近在看Java Socket相关的东西,看到其中一段示例程序,我居然运行结果跟书中的不一样,仔细检查代码并无写错,所以贴出来让大伙瞧瞧这个问题到底是什么情况。
服务器代码
package chapter01.example11;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class SimpleServer { public static void main(String[] args) throws IOException, InterruptedException { ServerSocket ss=new ServerSocket(8000); Socket s=ss.accept(); Thread.sleep(5000); InputStream in=s.getInputStream(); ByteArrayOutputStream buffer=new ByteArrayOutputStream(); byte[] buff=new byte[1024]; int len=-1; do { len=in.read(buff); if(len!=-1) buffer.write(buff,0,len); } while (len!=-1); System.out.println(new String(buffer.toByteArray())); } }package chapter01.example10;import java.io.IOException;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class SimpleClient { public static void main(String[] args) throws UnknownHostException, IOException { Socket s=new Socket("localhost",8000); s.setSoLinger(true, 3600); OutputStream out=s.getOutputStream(); StringBuffer sb=new StringBuffer(); for (int i = 0; i < 10000; i++) { sb.append(i); } out.write(sb.toString().getBytes()); System.out.println("开始关闭"); long begin=System.currentTimeMillis(); s.close(); long end=System.currentTimeMillis(); System.out.println("关闭Socket所用的时间未:"+(end-begin)+"ms"); } }