KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > ubik > net > udp > UDPConnection


1 package org.sapia.ubik.net.udp;
2
3 import org.sapia.ubik.net.Connection;
4 import org.sapia.ubik.net.ServerAddress;
5
6 import java.io.IOException JavaDoc;
7
8 import java.net.DatagramPacket JavaDoc;
9 import java.net.DatagramSocket JavaDoc;
10
11 import java.rmi.RemoteException JavaDoc;
12
13
14 /**
15  * @author Yanick Duchesne
16  * 16-Jun-2003
17  */

18 public class UDPConnection implements Connection {
19   protected int _bufsz;
20   private UDPServerAddress _addr;
21   private DatagramPacket JavaDoc _pack;
22   private DatagramSocket JavaDoc _sock;
23   private int _timeout;
24
25   /**
26    * Constructor for UDPConnection.
27    */

28   public UDPConnection(UDPServerAddress addr, int bufsz, int timeout) {
29     _addr = addr;
30     _bufsz = bufsz;
31     _timeout = timeout;
32   }
33
34   /**
35    * Constructor for UDPConnection.
36    */

37   public UDPConnection(DatagramSocket JavaDoc localServer, DatagramPacket JavaDoc pack,
38     int bufsz, int timeout) {
39     _addr = new UDPServerAddress(pack.getAddress(), pack.getPort());
40     _pack = pack;
41     _sock = localServer;
42     _bufsz = bufsz;
43     _timeout = timeout;
44   }
45
46   /**
47    * @see org.sapia.ubik.net.Connection#close()
48    */

49   public void close() {
50   }
51
52   /**
53    * @see org.sapia.ubik.net.Connection#getServerAddress()
54    */

55   public ServerAddress getServerAddress() {
56     return _addr;
57   }
58
59   /**
60    * @see org.sapia.ubik.net.Connection#receive()
61    */

62   public Object JavaDoc receive()
63     throws IOException JavaDoc, ClassNotFoundException JavaDoc, RemoteException JavaDoc {
64     if (_sock == null) {
65       _sock = new DatagramSocket JavaDoc(_addr.getPort());
66       _sock.setSoTimeout(_timeout);
67     }
68
69     DatagramPacket JavaDoc pack;
70
71     if (_pack == null) {
72       pack = new DatagramPacket JavaDoc(new byte[_bufsz], _bufsz);
73     } else {
74       pack = _pack;
75       _pack = null;
76     }
77
78     _sock.receive(pack);
79
80     return Util.fromDatagram(pack);
81   }
82
83   /**
84    * @see org.sapia.ubik.net.Connection#send(Object)
85    */

86   public void send(Object JavaDoc o) throws IOException JavaDoc, RemoteException JavaDoc {
87     byte[] bytes = Util.toBytes(o, _bufsz, getFactory());
88     send(bytes);
89   }
90
91   protected void send(byte[] bytes) throws IOException JavaDoc, RemoteException JavaDoc {
92     if (_sock == null) {
93       _sock = new DatagramSocket JavaDoc();
94       _sock.setSoTimeout(_timeout);
95     }
96
97     DatagramPacket JavaDoc pack = new DatagramPacket JavaDoc(bytes, 0, bytes.length,
98         _addr.getInetAddress(), _addr.getPort());
99     _sock.send(pack);
100   }
101
102   protected ObjectStreamFactory getFactory() {
103     return ObjectStreamFactory.DEFAULT_FACTORY;
104   }
105 }
106
Popular Tags