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