1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.http.nio.integration;
29
30 import java.net.ServerSocket;
31 import java.net.Socket;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.Future;
34
35 import org.apache.http.Consts;
36 import org.apache.http.HttpException;
37 import org.apache.http.HttpHost;
38 import org.apache.http.HttpRequest;
39 import org.apache.http.HttpResponse;
40 import org.apache.http.HttpVersion;
41 import org.apache.http.config.ConnectionConfig;
42 import org.apache.http.impl.nio.pool.BasicNIOConnFactory;
43 import org.apache.http.message.BasicHttpRequest;
44 import org.apache.http.nio.testserver.HttpClientNio;
45 import org.junit.After;
46 import org.junit.Assert;
47 import org.junit.Before;
48 import org.junit.Test;
49
50
51
52
53 public class TestClientOutOfSequenceResponse {
54
55 private ServerSocket server;
56 private HttpClientNio client;
57
58 @Before
59 public void setup() throws Exception {
60 server = new ServerSocket(0, 1);
61 client = new HttpClientNio(new BasicNIOConnFactory(ConnectionConfig.DEFAULT));
62 }
63
64 @After
65 public void cleanup() throws Exception {
66 if (client != null) {
67 client.shutdown();
68 }
69 if (server != null) {
70 server.close();
71 }
72 }
73
74 @Test
75 public void testOutOfSequenceResponse() throws Exception {
76 client.setMaxPerRoute(1);
77 client.setMaxTotal(1);
78
79 client.start();
80 final HttpHost target = new HttpHost("localhost", server.getLocalPort());
81 final HttpRequest get1 = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);
82 final Future<HttpResponse> future1 = client.execute(target, get1);
83 final HttpRequest get2 = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);
84 final Future<HttpResponse> future2 = client.execute(target, get2);
85
86 final Socket socket = server.accept();
87 Thread.sleep(100);
88 for (int i = 0; i < 3; ++i) {
89 socket.getOutputStream().write((
90 "HTTP/1.1 200 OK\r\n" +
91 "Content-Length: 0\r\n" +
92 "Connection: keep-alive\r\n\r\n").getBytes(Consts.UTF_8));
93 socket.getOutputStream().flush();
94 }
95
96 final HttpResponse response1 = future1.get();
97 Assert.assertEquals(200, response1.getStatusLine().getStatusCode());
98
99 try {
100 final HttpResponse response2 = future2.get();
101 Assert.assertEquals(200, response2.getStatusLine().getStatusCode());
102 } catch (final ExecutionException ex) {
103 Assert.assertTrue(ex.getCause() instanceof HttpException);
104 }
105 }
106
107 }