socket阻塞解决(java方案)

main test:

 1     public static void main(String[] args) {
 2         try {
 3             ServerSocket server = new ServerSocket(8080);
 4             while (true) {
 5                 Socket client = server.accept();
 6                 test1(client);
 7             }
 8         } catch (IOException e) {
 9             e.printStackTrace();
10         }
11     }

你可以使用浏览器测试是否阻塞!!

1、定长字符(1024字节读取,不够1024算读取完)

 1    public static void test1(Socket client) throws IOException {
 2         InputStream is = client.getInputStream();
 3         byte[] buffer = new byte[1024];//如果是1024的倍数,怎么搞...
 4         while (true) {
 5             int flag = is.read(buffer);
 6             System.out.println(new String(buffer,0,flag,"UTF-8"));
 7             if (flag < 1024) {
 8                 break;
 9             }
10         }
11         client.close();
12 
13     }

 

2、SocketTimeoutException+ socket.shutdownOutput

 1     public static void test2(Socket client) throws IOException {
 2         client.setSoTimeout(500);
 3         BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
 4         try {
 5             String content = br.readLine();
 6             while (content != null) {
 7                 System.out.println(content);
 8                 content = br.readLine();
 9             }
10         } catch (SocketTimeoutException e) {
11             client.shutdownOutput();
12         }
13         client.close();
14     }

 

posted @ 2016-02-28 16:18  徐徐徐徐徐徐  阅读(1339)  评论(0)    收藏  举报