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 package javax.microedition.io;
28
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.OutputStream;
32
33 public class SocketConnectionTest extends BaseGCFTestCase {
34
35 private static final String loopbackHost = TEST_HOST;
36
37
38 private static final String loopbackPort = "9127";
39
40 private static final String serverPort = "7127";
41
42
43 private void runLoopbackTest(String url) throws IOException {
44 System.out.println("Connecting to " + url);
45 SocketConnection sc = (SocketConnection) Connector.open(url);
46
47 try {
48 sc.setSocketOption(SocketConnection.LINGER, 5);
49
50 InputStream is = sc.openInputStream();
51 OutputStream os = sc.openOutputStream();
52
53 String testData = "OK\r\n";
54
55 os.write(testData.getBytes());
56 os.flush();
57
58 StringBuffer buf = new StringBuffer();
59
60 int ch = 0;
61 int count = 0;
62 while (ch != -1) {
63 ch = is.read();
64 buf.append((char)ch);
65 count ++;
66 if (count >= testData.length()) {
67 break;
68 }
69 }
70
71 assertEquals("Data received", buf.toString(), testData);
72
73 is.close();
74 os.close();
75 } finally {
76 sc.close();
77 }
78
79 }
80
81 public void testLoopback() throws IOException {
82 runLoopbackTest("socket://" + loopbackHost + ":" + loopbackPort);
83 }
84
85 private class ServerThread extends Thread {
86
87 ServerSocketConnection scn;
88
89 boolean started = true;
90
91 boolean finished = true;
92
93 ServerThread(ServerSocketConnection scn) {
94 super.setDaemon(true);
95 this.scn = scn;
96 }
97
98 public void run() {
99 try {
100
101 SocketConnection sc = (SocketConnection) scn.acceptAndOpen();
102
103 InputStream is = sc.openInputStream();
104 OutputStream os = sc.openOutputStream();
105
106 int ch = 0;
107 int count = 0;
108 while (ch != -1) {
109 ch = is.read();
110 if (ch == -1) {
111 break;
112 }
113 os.write(ch);
114 os.flush();
115 count ++;
116 }
117 } catch(IOException e) {
118 e.printStackTrace();
119 } finally {
120 finished = true;
121 }
122 }
123 }
124
125 static public void assertNotEquals(String message, String expected, String actual) {
126 assertFalse(message + " [" + expected + " == "+ actual + "]", expected.equals(actual));
127 }
128
129 public void testServerSocketConnection() throws IOException, InterruptedException {
130 ServerSocketConnection scn = (ServerSocketConnection) Connector.open("socket://:" + serverPort);
131
132 try {
133 ServerThread t = new ServerThread(scn);
134 t.start();
135 while (!t.started) {
136 Thread.sleep(20);
137 }
138 assertEquals("Server Port", Integer.valueOf(serverPort).intValue(), scn.getLocalPort());
139 assertNotEquals("Server Host", "0.0.0.0", scn.getLocalAddress());
140 assertNotEquals("Server Host", "localhost", scn.getLocalAddress());
141
142
143 runLoopbackTest("socket://" + scn.getLocalAddress() + ":" + scn.getLocalPort());
144 } finally {
145 scn.close();
146 }
147 }
148 }