PR target/27599
[official-gcc.git] / libjava / classpath / testsuite / java.net / SocketSendReceiveTest.java
blob15ab983a44a668d6f693514be935f14952b6ad45
1 import java.net.*;
2 import java.io.*;
4 /*
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.
8 */
10 public class SocketSendReceiveTest
11 implements Runnable
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;
18 void send()
19 throws Exception
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);
27 out.flush();
28 sender.close();
30 void receive()
31 throws Exception
33 ServerSocket socket = new ServerSocket(port);
35 synchronized(this) {
36 notifyAll();
39 Socket connection = socket.accept();
40 DataInputStream in = new DataInputStream(connection.getInputStream());
42 byte[] buffer = new byte[100];
44 int length = in.read(buffer);
46 connection.close();
47 socket.close();
49 received = new String(buffer, 0, length);
51 count++;
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 + "\"");
61 public void run()
63 String name = Thread.currentThread().getName();
64 if (name.equals("timer")) {
65 try {
66 Thread.sleep(10000);
67 } catch (InterruptedException e){}
68 System.out.println("FAILED: timer triggered");
69 System.exit(0);
71 try {
72 receive();
73 } catch (Exception e) {
74 System.out.println("FAILED: receiver (port "+port + "): " + e);
75 System.exit(0);
78 public static void main(String args[])
80 try {
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");
88 timer_thread.start();
90 synchronized(receiver) {
91 receiver_thread.start();
92 receiver.wait();
94 try {
95 sender.send();
96 } catch (Exception e) {
97 System.out.println("FAILED: receiver (port "+port + "): " + e);
98 System.exit(0);
100 receiver_thread.join();
102 if (0 == count)
103 throw new Exception("Nothing received");
105 System.out.println("PASSED: Socket send/receive count="+count+
106 " message="+received);
107 System.exit(0);
108 } catch (Exception e) {
109 System.out.println("FAILED: " + e);
110 System.exit(0);