aboutsummaryrefslogtreecommitdiff
path: root/tests/TestNetSwing.java
blob: 7aed6e23a17a8a9f09399d0360aba7dbccbf51d2 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
 * TestNetSwing , a network Ivy domain checker.
 * @author Yannick Jestin <mailto:jestin@cena.fr>
 *
 * (c) CENA
 * A simple Swing application in order to check a network
 *
 * Changelog:
 * 1.2.8
 *   - apache regexp instead of gnu regexp
 */
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import fr.dgac.ivy.*;
import java.util.regex.*;
import gnu.getopt.*;

class TestNetSwing implements Runnable {

  private JFrame frame;
  private JLabel receive;
  private JButton send;
  private int alpha=0;
  private Color color;
  private static int FADINGSTEP = 20;
  private static int FADINGSLEEP = 100;
  private static int DEFAULT_RED=200;
  private static int DEFAULT_GREEN=10;
  private static int DEFAULT_BLUE=10;
  private static int DEFAULT_ALPHA=255;
  private static Color DEFAULT_COLOR = 
      new Color(DEFAULT_RED,DEFAULT_GREEN,DEFAULT_BLUE,DEFAULT_ALPHA);

  private Ageing age;
  private String domainAddr="none";
  private int port=0;
  private int serial=1;
  private boolean watcherrunning = false;
  private volatile Thread watcherThread;
  private boolean isMulticastAddress = false;
  private Thread broadcastListener ;
  private DatagramSocket broadcast;	/* supervision socket */
    // it can also be a MulticastSocket, which inherits from the previous

  public TestNetSwing(String da,int p) {
    this.domainAddr=da;
    this.port=p;
    createBroadcastListener();
    frame = new JFrame("TestNet "+domainAddr+":"+port);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container cp = frame.getContentPane();
    cp.setLayout(new GridLayout(0,1));
    cp.add(send = new JButton("send packet to "+domainAddr+":"+port));
    send.addActionListener( new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        send("hello",domainAddr,port);
      }
    });
    cp.add(receive = new JLabel(""));
    boolean sel = false;
    frame.pack();
    age=new Ageing();
    frame.setVisible(true);
  }
  
  public void run() {
    byte buf[] = new byte[256];
    Thread thisThread=Thread.currentThread();
    for (int i=0;i<buf.length;i++) { buf[i]=10; }
    DatagramPacket packet=new DatagramPacket(buf, 256);
    String s = "Server waiting for Broadcast on "+domainAddr+":"+port;
    s+=(isMulticastAddress)?" (TCP multicast)":" (UDP broadcast)"; 
    System.out.println(s);
    while( watcherThread==thisThread) try {
	broadcast.receive(packet);
	String msg = new String(buf) ;
	// clean up the buffer after each message
	for (int i=0;i<buf.length;i++) { buf[i]=10; }
	InetAddress remotehost = packet.getAddress();
	updateLabel("("+(serial++)+") "+ remotehost.getHostName()+":"+msg);
    } catch (java.io.InterruptedIOException jii ){
      if (watcherThread!=thisThread) break;
    } catch (java.io.IOException ioe ){
     System.err.println("IvyWatcher IOException "+ ioe.getMessage() );
    }
    broadcast.close();
    System.out.println("Server normal shutdown");
  }
  
  synchronized void stop() {
    Thread t = watcherThread;
    watcherThread = null;
    if (t!=null) { t.interrupt(); }
  }

  private void updateLabel(String text) {
    if (text==null) return;
    int i = text.indexOf(10);
    if (i>0) { receive.setText(text.substring(0,i)); }
    else { receive.setText(text); }
    alpha=DEFAULT_ALPHA;
    color=DEFAULT_COLOR;
    receive.setForeground(color);
  }

  private static void send(String data, String domain,int port) {
    try {
      DatagramSocket send;
      InetAddress group = InetAddress.getByName(domain);
      send = new MulticastSocket(port);
      if (group.isMulticastAddress()) { ((MulticastSocket)send).joinGroup(group); }
      DatagramPacket packet = new DatagramPacket(
	  data.getBytes(),
	  data.length(),
	  group,
	  send.getLocalPort() );
      //System.out.println("Client sends Broadcast to "+net+":"+port+" ("+packet.getLength()+") ["+data+"]");
      send.send(packet);
    } catch ( UnknownHostException e ) {
      System.out.println("Broadcast sent on unknown network "+ e.getMessage());
    } catch ( IOException e ) {
      System.out.println("Broadcast error " + e.getMessage() );
    }
  }

  private void createBroadcastListener() {
    try {
      InetAddress group = InetAddress.getByName(domainAddr);
      if (group.isMulticastAddress()) {
        isMulticastAddress = true;
        broadcast = new MulticastSocket(port); // create the UDP socket
	((MulticastSocket)broadcast).joinGroup(group);
      } else {
        broadcast = new MulticastSocket(port); // create the UDP socket
      }
    } catch ( IOException e ) {
      System.out.println("MulticastSocket I/O error" + e );
      e.printStackTrace();
      System.exit(0);
    } 
    try {
      broadcast.setSoTimeout(Ivy.TIMEOUTLENGTH);
    } catch ( java.net.SocketException jns ) {
      System.out.println("IvyWatcher setSoTimeout error" + jns.getMessage() );
    }
    watcherThread = new Thread(this); 
    watcherThread.start();
  }

  private class Ageing implements Runnable {
    boolean encore = true;
    public Ageing() {
      new Thread(this).start();
    }
    public void run() {
      while (encore) {
	try {
	  java.lang.Thread.sleep(FADINGSLEEP);
	} catch (InterruptedException ie) {
	}
	alpha-=FADINGSTEP;
	String s = receive.getText();
	if (alpha<0) {
	  alpha=0;
	  receive.setText(null);
	  s=null;
	}
	if (s!=null) { receive.setForeground(new Color(DEFAULT_RED,DEFAULT_GREEN,DEFAULT_BLUE,alpha)); }
      }
    }
    public void stop(){ encore=false; }
  }

  /*
   * copied verbatim from IvyWatcher , I should put TestNetSwing *in* the
   * distribution itself ...
   */
  static String getDomain(String net) throws IvyException {
    // System.out.println("debug: net=[" + net+ "]");
    int sep_index = net.lastIndexOf( ":" );
    if ( sep_index != -1 ) { net = net.substring(0,sep_index); }
    try {
      Pattern numbersPoint = Pattern.compile("([0-9]|\\.)+");
      if (!numbersPoint.matcher(net).matches()) {
	// traceDebug("should only have numbers and point ? I won't add anything... " + net);
	return net;
      }
      net += ".255.255.255";
      Pattern exp = Pattern.compile( "^(\\d+\\.\\d+\\.\\d+\\.\\d+).*");
      Matcher m = exp.matcher(net);
      if (!m.matches()) {
	System.out.println("Bad broascat addr " + net);
	throw new IvyException("bad broadcast addr");
      }
      net=m.group(1);
    } catch ( PatternSyntaxException e ){
      System.out.println(e);
      System.exit(0);
    }
    // System.out.println("debug: returning net=[" + net+ "]");
    return net;
  }

  static int getPort(String net) { // returns 0 if no port is set
    int sep_index = net.lastIndexOf( ":" );
    int port= ( sep_index == -1 ) ? 0 :Integer.parseInt( net.substring( sep_index +1 ));
    // System.out.println("net: ["+net+"]\nsep_index: "+sep_index+"\nport: "+port);
    return port;
  }


  public static final String helpmsg = "usage: java TestNetSwing [options]\n\t-b BUS\tspecifies the Ivy bus domain\n\t-h\thelp\n\n";
  public static void main(String[] args) throws IvyException {
    Getopt opt = new Getopt("TestNetSwing",args,"b:h");
    int c;
    String domainstring = Ivy.getDomain(null);
    while ((c = opt.getopt()) != -1) switch (c) {
    case 'b':
      domainstring=opt.getOptarg();
      break;
    case 'h':
    default:
	System.out.println(helpmsg);
	System.exit(0);
    } // getopt
    new TestNetSwing(getDomain(domainstring),getPort(domainstring));
  }

} // class TestNetSwing
/* EOF */