Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 4e593e1cf698f72e67b82ff08cae56da01b56fd2 (plain) (blame)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
// ========================================================================
// Copyright 2011-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
//     The Eclipse Public License is available at
//     http://www.eclipse.org/legal/epl-v10.html
//
//     The Apache License v2.0 is available at
//     http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
//========================================================================
package org.eclipse.jetty.websocket.client;

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.eclipse.jetty.websocket.api.WebSocketConnection;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.client.blockhead.BlockheadServer;
import org.eclipse.jetty.websocket.client.blockhead.BlockheadServer.ServerConnection;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;

@Ignore("Client not yet functional")
public class WebSocketClientTest
{
    public static class TrackingSocket extends WebSocketAdapter
    {
        public AtomicBoolean open = new AtomicBoolean(false);
        public AtomicInteger close = new AtomicInteger(-1);
        public StringBuilder closeMessage = new StringBuilder();
        public CountDownLatch openLatch = new CountDownLatch(1);
        public CountDownLatch closeLatch = new CountDownLatch(1);
        public CountDownLatch dataLatch = new CountDownLatch(1);
        public BlockingQueue<String> messageQueue = new BlockingArrayQueue<String>();

        public void assertClose(int expectedStatusCode, String expectedReason)
        {
            assertCloseCode(expectedStatusCode);
            assertCloseReason(expectedReason);
        }

        public void assertCloseCode(int expectedCode)
        {
            Assert.assertThat("Close Code",close.get(),is(expectedCode));
        }

        private void assertCloseReason(String expectedReason)
        {
            Assert.assertThat("Close Reaosn",closeMessage.toString(),is(expectedReason));
        }

        public void assertIsOpen()
        {
            assertWasOpened();
            assertNotClosed();
        }

        public void assertNotClosed()
        {
            Assert.assertThat("Close Code",close.get(),is(-1));
        }

        public void assertNotOpened()
        {
            Assert.assertThat("Opened State",open.get(),is(false));
        }

        public void assertWasOpened()
        {
            Assert.assertThat("Opened State",open.get(),is(true));
        }

        @Override
        public void onWebSocketBinary(byte[] payload, int offset, int len)
        {
            dataLatch.countDown();
        }

        @Override
        public void onWebSocketClose(int statusCode, String reason)
        {
            close.set(statusCode);
            closeMessage.append(reason);
            closeLatch.countDown();
        }

        @Override
        public void onWebSocketConnect(WebSocketConnection connection)
        {
            open.set(true);
            openLatch.countDown();
        }

        @Override
        public void onWebSocketText(String message)
        {
            dataLatch.countDown();
            messageQueue.add(message);
        }
    }

    private BlockheadServer server;

    @Before
    public void startServer() throws Exception
    {
        server = new BlockheadServer();
        server.start();
    }

    @After
    public void stopServer() throws Exception
    {
        server.close();
    }

    @Test
    public void testAsyncConnectionRefused() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();

        TrackingSocket wsocket = new TrackingSocket();

        // Intentionally bad port
        URI wsUri = new URI("ws://127.0.0.1:1");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        Throwable error = null;
        try
        {
            future.get(1,TimeUnit.SECONDS);
            Assert.fail("Expected ExecutionException");
        }
        catch (ExecutionException e)
        {
            error = e.getCause();
        }

        wsocket.assertNotOpened();
        wsocket.assertCloseCode(StatusCode.NO_CLOSE);
        Assert.assertTrue(error instanceof ConnectException);
    }

    @Test
    public void testBadHandshake() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        ServerConnection connection = server.accept();
        connection.respond("HTTP/1.1 404 NOT FOUND\r\n\r\n");

        Throwable error = null;
        try
        {
            future.get(250,TimeUnit.MILLISECONDS);
            Assert.fail();
        }
        catch (ExecutionException e)
        {
            error = e.getCause();
        }

        wsocket.assertNotOpened();
        wsocket.assertCloseCode(StatusCode.PROTOCOL);
        Assert.assertTrue(error instanceof IOException);
        Assert.assertTrue(error.getMessage().indexOf("404 NOT FOUND") > 0);

    }

    @Test
    public void testBadUpgrade() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        ServerConnection connection = server.accept();
        connection.respond("HTTP/1.1 101 Upgrade\r\n" + "Sec-WebSocket-Accept: rubbish\r\n" + "\r\n");

        Throwable error = null;
        try
        {
            future.get(250,TimeUnit.MILLISECONDS);
            Assert.fail();
        }
        catch (ExecutionException e)
        {
            error = e.getCause();
        }

        wsocket.assertNotOpened();
        wsocket.assertCloseCode(StatusCode.PROTOCOL);
        Assert.assertTrue(error instanceof IOException);
        Assert.assertThat("Error Message",error.getMessage(),containsString("Bad Sec-WebSocket-Accept"));
    }

    @Test
    public void testBadURL() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();

        TrackingSocket wsocket = new TrackingSocket();
        try
        {
            // Intentionally bad scheme in URI
            URI wsUri = new URI("http://localhost:8080");

            client.connect(wsUri,wsocket); // should toss exception

            Assert.fail("Expected IllegalArgumentException");
        }
        catch (IllegalArgumentException e)
        {
            // expected path
            wsocket.assertNotOpened();
        }
    }

    @Test
    public void testBlockReceiving() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();
        client.getPolicy().setIdleTimeout(60000);

        final AtomicBoolean open = new AtomicBoolean(false);
        final AtomicInteger close = new AtomicInteger();
        final CountDownLatch _latch = new CountDownLatch(1);
        final StringBuilder closeMessage = new StringBuilder();
        final Exchanger<String> exchanger = new Exchanger<String>();

        WebSocketListener socket = new WebSocketAdapter()
        {
            @Override
            public void onWebSocketClose(int statusCode, String reason)
            {
                close.set(statusCode);
                closeMessage.append(reason);
                _latch.countDown();
            }

            @Override
            public void onWebSocketConnect(WebSocketConnection connection)
            {
                open.set(true);
            }

            @Override
            public void onWebSocketText(String message)
            {
                try
                {
                    exchanger.exchange(message);
                }
                catch (InterruptedException e)
                {
                    // e.printStackTrace();
                }
            }
        };

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,socket);

        ServerConnection sconnection = server.accept();
        sconnection.setSoTimeout(60000);

        WebSocketConnection connection = future.get(250,TimeUnit.MILLISECONDS);
        Assert.assertNotNull(connection);
        Assert.assertTrue(open.get());
        Assert.assertEquals(0,close.get());

        // define some messages to send server to client
        byte[] send = new byte[]
        { (byte)0x81, (byte)0x05, (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };
        final int messages = 100000;
        final AtomicInteger m = new AtomicInteger();

        // Set up a consumer of received messages that waits a while before consuming
        Thread consumer = new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    Thread.sleep(200);
                    while (m.get() < messages)
                    {
                        String msg = exchanger.exchange(null);
                        if ("Hello".equals(msg))
                        {
                            m.incrementAndGet();
                        }
                        else
                        {
                            throw new IllegalStateException("exchanged " + msg);
                        }
                        if ((m.get() % 1000) == 0)
                        {
                            // Artificially slow reader
                            Thread.sleep(10);
                        }
                    }
                }
                catch (InterruptedException e)
                {
                    return;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        };
        consumer.start();

        long start = System.currentTimeMillis();
        for (int i = 0; i < messages; i++)
        {
            sconnection.write(send,0,send.length);
            sconnection.flush();
        }

        while (consumer.isAlive())
        {
            Thread.sleep(10);
        }

        // Duration of the read operation.
        long readDur = (System.currentTimeMillis() - start);

        Assert.assertThat("read duration",readDur,greaterThan(1000L)); // reading was blocked
        Assert.assertEquals(m.get(),messages);

        // Close with code
        start = System.currentTimeMillis();
        sconnection.write(new byte[]
        { (byte)0x88, (byte)0x02, (byte)4, (byte)87 },0,4);
        sconnection.flush();

        _latch.await(10,TimeUnit.SECONDS);
        Assert.assertTrue((System.currentTimeMillis() - start) < 5000);
        Assert.assertEquals(1002,close.get());
        Assert.assertEquals("Invalid close code 1111",closeMessage.toString());
    }

    @Test
    public void testBlockSending() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();
        client.getPolicy().setIdleTimeout(10000);

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        final ServerConnection ssocket = server.accept();
        ssocket.upgrade();

        WebSocketConnection connection = future.get(250,TimeUnit.MILLISECONDS);
        Assert.assertNotNull(connection);
        wsocket.assertWasOpened();
        wsocket.assertNotClosed();

        final int messages = 200000;
        final AtomicLong totalB = new AtomicLong();

        Thread consumer = new Thread()
        {
            @Override
            public void run()
            {
                // Thread.sleep is for artificially poor performance reader needed for this testcase.
                try
                {
                    Thread.sleep(200);
                    byte[] recv = new byte[32 * 1024];

                    int len = 0;
                    while (len >= 0)
                    {
                        totalB.addAndGet(len);
                        len = ssocket.getInputStream().read(recv,0,recv.length);
                        Thread.sleep(10);
                    }
                }
                catch (InterruptedException e)
                {
                    return;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        };
        consumer.start();

        // Send lots of messages client to server
        long start = System.currentTimeMillis();
        String mesg = "This is a test message to send";
        for (int i = 0; i < messages; i++)
        {
            connection.write(null,new FutureCallback<Void>(),mesg);
        }

        // Duration for the write phase
        long writeDur = (System.currentTimeMillis() - start);

        // wait for consumer to complete
        while (totalB.get() < (messages * (mesg.length() + 6L)))
        {
            Thread.sleep(10);
        }

        Assert.assertThat("write duration",writeDur,greaterThan(1000L)); // writing was blocked
        Assert.assertEquals(messages * (mesg.length() + 6L),totalB.get());

        consumer.interrupt();
    }

    @Test
    public void testConnectionNotAccepted() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        // Intentionally not accept incoming socket.
        // server.accept();

        try
        {
            future.get(250,TimeUnit.MILLISECONDS);
            Assert.fail("Should have Timed Out");
        }
        catch (TimeoutException e)
        {
            // Expected Path
            wsocket.assertNotOpened();
            wsocket.assertCloseCode(StatusCode.NO_CLOSE);
        }
    }

    @Test
    public void testConnectionTimeout() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        ServerConnection ssocket = server.accept();
        Assert.assertNotNull(ssocket);
        // Intentionally don't upgrade
        // ssocket.upgrade();

        try
        {
            future.get(250,TimeUnit.MILLISECONDS);
            Assert.fail("Expected Timeout Exception");
        }
        catch (TimeoutException e)
        {
            // Expected path
            wsocket.assertNotOpened();
            wsocket.assertCloseCode(StatusCode.NO_CLOSE);
        }
    }

    @Test
    public void testIdle() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();
        client.getPolicy().setIdleTimeout(500);

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        ServerConnection ssocket = server.accept();
        ssocket.upgrade();

        WebSocketConnection connection = future.get(250,TimeUnit.MILLISECONDS);
        Assert.assertNotNull(connection);
        wsocket.assertWasOpened();
        wsocket.assertNotClosed();

        long start = System.currentTimeMillis();
        wsocket.closeLatch.await(10,TimeUnit.SECONDS);
        Assert.assertTrue((System.currentTimeMillis() - start) < 5000);
        wsocket.assertCloseCode(StatusCode.NORMAL);
    }

    @Test
    public void testMessageBiggerThanBufferSize() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        int bufferSize = 512;
        factory.getPolicy().setBufferSize(512);
        WebSocketClient client = factory.newWebSocketClient();

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        ServerConnection ssocket = server.accept();
        ssocket.upgrade();

        Assert.assertTrue(wsocket.openLatch.await(1,TimeUnit.SECONDS));

        int length = bufferSize + (bufferSize / 2); // 1.5 times buffer size
        ssocket.write(0x80 | 0x01); // FIN + TEXT
        ssocket.write(0x7E); // No MASK and 2 bytes length
        ssocket.write(length >> 8); // first length byte
        ssocket.write(length & 0xFF); // second length byte
        for (int i = 0; i < length; ++i)
        {
            ssocket.write('x');
        }
        ssocket.flush();

        Assert.assertTrue(wsocket.dataLatch.await(1000,TimeUnit.SECONDS));
    }

    @Test
    public void testNotIdle() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();
        client.getPolicy().setIdleTimeout(500);

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        ServerConnection ssocket = server.accept();
        ssocket.upgrade();

        WebSocketConnection connection = future.get(250,TimeUnit.MILLISECONDS);
        Assert.assertNotNull(connection);

        wsocket.assertIsOpen();

        // Send some messages client to server
        byte[] recv = new byte[1024];
        int len = -1;
        for (int i = 0; i < 10; i++)
        {
            Thread.sleep(250);
            connection.write(null,new FutureCallback<Void>(),"Hello");
            len = ssocket.getInputStream().read(recv,0,recv.length);
            Assert.assertTrue(len > 0);
        }

        // Send some messages server to client
        byte[] send = new byte[]
        { (byte)0x81, (byte)0x02, (byte)'H', (byte)'i' };

        for (int i = 0; i < 10; i++)
        {
            Thread.sleep(250);
            ssocket.write(send,0,send.length);
            ssocket.flush();
            Assert.assertEquals("Hi",wsocket.messageQueue.poll(1,TimeUnit.SECONDS));
        }

        // Close with code
        long start = System.currentTimeMillis();
        ssocket.write(new byte[]
        { (byte)0x88, (byte)0x02, (byte)4, (byte)87 },0,4);
        ssocket.flush();

        wsocket.closeLatch.await(10,TimeUnit.SECONDS);
        Assert.assertTrue((System.currentTimeMillis() - start) < 5000);
        wsocket.assertClose(StatusCode.PROTOCOL,"Invalid close code 1111");
    }

    @Test
    public void testUpgradeThenTCPClose() throws Exception
    {
        WebSocketClientFactory factory = new WebSocketClientFactory();
        WebSocketClient client = factory.newWebSocketClient();

        TrackingSocket wsocket = new TrackingSocket();

        URI wsUri = new URI("ws://127.0.0.1:" + server.getPort() + "/");
        Future<WebSocketConnection> future = client.connect(wsUri,wsocket);

        ServerConnection ssocket = server.accept();
        ssocket.upgrade();

        WebSocketConnection connection = future.get(250,TimeUnit.MILLISECONDS);
        Assert.assertNotNull(connection);

        wsocket.assertIsOpen();

        ssocket.close();
        wsocket.openLatch.await(10,TimeUnit.SECONDS);

        wsocket.assertCloseCode(StatusCode.NO_CLOSE);
    }

    @Test
    public void testURIWithDefaultPort() throws Exception
    {
        URI uri = new URI("ws://localhost");

        InetSocketAddress addr = WebSocketClient.toSocketAddress(uri);
        Assert.assertThat("URI (" + uri + ").host",addr.getHostName(),is("localhost"));
        Assert.assertThat("URI (" + uri + ").port",addr.getPort(),is(80));
    }

    @Test
    public void testURIWithDefaultWSSPort() throws Exception
    {
        URI uri = new URI("wss://localhost");
        InetSocketAddress addr = WebSocketClient.toSocketAddress(uri);
        Assert.assertThat("URI (" + uri + ").host",addr.getHostName(),is("localhost"));
        Assert.assertThat("URI (" + uri + ").port",addr.getPort(),is(443));
    }
}

Back to the top