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
|
package com.koushikdutta.async.test;
import com.koushikdutta.async.AsyncServer;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpClient.WebSocketConnectCallback;
import com.koushikdutta.async.http.WebSocket;
import com.koushikdutta.async.http.WebSocket.StringCallback;
import com.koushikdutta.async.http.libcore.RequestHeaders;
import com.koushikdutta.async.http.server.AsyncHttpServer;
import com.koushikdutta.async.http.server.AsyncHttpServer.WebSocketRequestCallback;
import junit.framework.TestCase;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class WebSocketTests extends TestCase {
AsyncHttpServer httpServer;
@Override
protected void setUp() throws Exception {
super.setUp();
httpServer = new AsyncHttpServer();
httpServer.setErrorCallback(new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
fail();
}
});
httpServer.listen(AsyncServer.getDefault(), 5000);
httpServer.websocket("/ws", new WebSocketRequestCallback() {
@Override
public void onConnected(final WebSocket webSocket, RequestHeaders headers) {
webSocket.setStringCallback(new StringCallback() {
@Override
public void onStringAvailable(String s) {
webSocket.send(s);
}
});
}
});
}
private static final long TIMEOUT = 10000L;
public void testWebSocket() throws Exception {
final Semaphore semaphore = new Semaphore(0);
AsyncHttpClient.getDefaultInstance().websocket("http://localhost:5000/ws", null, new WebSocketConnectCallback() {
@Override
public void onCompleted(Exception ex, WebSocket webSocket) {
webSocket.send("hello");
webSocket.setStringCallback(new StringCallback() {
@Override
public void onStringAvailable(String s) {
assertEquals(s, "hello");
semaphore.release();
}
});
}
});
assertTrue(semaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS));
}
// public void testDisconnect() throws Exception {
// final Semaphore semaphore = new Semaphore(0);
//
// AsyncHttpClient.getDefaultInstance().websocket("http://192.168.1.2:3005", null, new WebSocketConnectCallback() {
// @Override
// public void onCompleted(Exception ex, WebSocket webSocket) {
// webSocket.setClosedCallback(new CompletedCallback() {
// @Override
// public void onCompleted(Exception ex) {
// semaphore.release();
// }
// });
// }
// });
//
// assertTrue(semaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS));
// }
@Override
protected void tearDown() throws Exception {
super.tearDown();
httpServer.stop();
}
}
|