5 * Start one thread for receiving a packet, wait for it to set up,
6 * send a packet to it, and wait until it completes. Compare the
7 * packet to make sure it came thru without errors.
10 public class SocketSendReceiveTest
13 public static final int port
= 4000 + (int)(java
.lang
.Math
.random() * 2000);
14 public static final String message
= "hello";
15 public static int count
= 0;
16 public static String received
;
21 InetAddress local
= InetAddress
.getLocalHost();
22 Socket sender
= new Socket(local
, port
);
23 byte []message_bytes
= message
.getBytes();
25 DataOutputStream out
= new DataOutputStream(sender
.getOutputStream());
26 out
.write(message_bytes
, 0, message_bytes
.length
);
33 ServerSocket socket
= new ServerSocket(port
);
39 Socket connection
= socket
.accept();
40 DataInputStream in
= new DataInputStream(connection
.getInputStream());
42 byte[] buffer
= new byte[100];
44 int length
= in
.read(buffer
);
49 received
= new String(buffer
, 0, length
);
52 if ( message
.length() != received
.length() )
53 throw new Exception("Receved "+ received
.length()+
54 " bytes but sent "+message
.length() + " bytes");
56 if ( ! message
.equals(received
) )
57 throw new Exception("Receved \""+ received
+
58 "\" but sent \""+message
+ "\"");
63 String name
= Thread
.currentThread().getName();
64 if (name
.equals("timer")) {
67 } catch (InterruptedException e
){}
68 System
.out
.println("FAILED: timer triggered");
73 } catch (Exception e
) {
74 System
.out
.println("FAILED: receiver (port "+port
+ "): " + e
);
78 public static void main(String args
[])
81 SocketSendReceiveTest sender
= new SocketSendReceiveTest();
82 SocketSendReceiveTest receiver
= new SocketSendReceiveTest();
83 Thread receiver_thread
= new Thread(receiver
);
85 /* Make sure the test terminates even if it hangs on network */
86 SocketSendReceiveTest timer
= new SocketSendReceiveTest();
87 Thread timer_thread
= new Thread(timer
, "timer");
90 synchronized(receiver
) {
91 receiver_thread
.start();
96 } catch (Exception e
) {
97 System
.out
.println("FAILED: receiver (port "+port
+ "): " + e
);
100 receiver_thread
.join();
103 throw new Exception("Nothing received");
105 System
.out
.println("PASSED: Socket send/receive count="+count
+
106 " message="+received
);
108 } catch (Exception e
) {
109 System
.out
.println("FAILED: " + e
);