4 * Copyright 2015 TJ <hacker@iam.tj>.
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 package uk.ac.ntu.n0521366.wsyd.libs.net;
26 import java.text.MessageFormat;
27 import java.io.IOException;
28 import java.io.ObjectStreamException;
29 import java.net.InetSocketAddress;
30 import java.net.DatagramSocket;
31 import java.net.DatagramPacket;
32 import java.net.SocketException;
33 import java.net.SocketTimeoutException;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36 import java.util.logging.LogRecord;
37 import uk.ac.ntu.n0521366.wsyd.libs.message.MessageLogRecord;
42 * Dual-use multithreading network UDP server that can be used stand-alone
43 * or in a Swing GUI application as a background worker thread.
45 * @see NetworkServerAbstract
46 * @author TJ <hacker@iam.tj>
48 public class NetworkServerUDP extends NetworkServerAbstract {
52 private DatagramSocket _datagramSocket = null;
55 * Maximum size of UDP packet payload
57 public static final int UDP_PAYLOAD_SIZE_MAX = 65507;
60 * Construct the server with a Logger.
62 * No socket is opened.
64 * @param socketAddress The socket to listen on
65 * @param title source identifier for use in log messages and sent NetworkMessage objects
66 * @param logger An instance of Logger to be used by all objects of this class
68 public NetworkServerUDP(WSYD_SocketAddress socketAddress, String title, Logger logger) {
69 super(socketAddress, title, logger);
73 * Construct the server without a Logger.
75 * No socket is opened.
77 * @param socketAddress The socket to listen on
78 * @param title source identifier for use in log messages and sent NetworkMessage objects
80 public NetworkServerUDP(WSYD_SocketAddress socketAddress, String title) {
81 super(socketAddress, title);
85 * Get the DatagramSocket for this service.
89 public DatagramSocket getSocket() {
90 return this._datagramSocket;
94 * Open the socket ready for accepting packets.
96 * It should also set a reasonable socket timeout with a call to setSoTimeout()
97 * to prevent unnecessary blocking.
99 * @throws SocketException
102 public void serverOpen() throws SocketException {
103 _datagramSocket = new DatagramSocket(_socketAddress.getPort(), _socketAddress.getAddress());
104 _datagramSocket.setSoTimeout(100); // 1/10th second blocking timeout on receive()
110 * @throws SocketException
113 public void serverClose() throws SocketException {
114 // use 'this' to ensure sub-classes refer to their own '_datagramSocket' when inheriting this method
115 if (this._datagramSocket != null)
116 this._datagramSocket.close();
120 * Accept packet from remote hosts.
124 * @return true if the server should continue listening
127 public boolean serverListen() {
128 boolean result = false;
129 byte[] dataReceive = new byte[UDP_PAYLOAD_SIZE_MAX];
130 DatagramPacket packetReceive = new DatagramPacket(dataReceive, dataReceive.length);
131 NetworkMessage messageReceived;
133 /* blocks waiting for packet until socket timeout expires, when SocketTimeOut
134 * exception is thrown.
136 if (this.getSocket() != null)
137 this.getSocket().receive(packetReceive);
139 throw new SocketTimeoutException("No socket available!");
141 // packet was received
142 messageReceived = NetworkMessage.deserialize(packetReceive.getData());
145 if (!messageReceived.getSender().equals(_title)) {
147 // add or update the last-seen time of the Sender host in the known services map
148 LastSeenHost host = new LastSeenHost((InetSocketAddress)packetReceive.getSocketAddress());
149 this._serviceToHostMap.put(messageReceived.getSender(), host);
150 log(Level.FINEST, _title, MessageFormat.format("Added \"{0}\" to service map", messageReceived.getSender()));
152 // pass the message to the process() method in the Owner Thread
153 publish(messageReceived);
155 result = true; // successful
158 } catch (SocketTimeoutException e) {
159 result = false; // no packet received
160 if (this._simulate) {
161 LogRecord record = new LogRecord(Level.FINEST, "Simulated received message");
162 record.setSourceClassName("Simulator");
163 record.setMillis(System.currentTimeMillis());
164 MessageLogRecord m = new MessageLogRecord(record);
165 publish(new NetworkMessage("Log","Simulator",m));
169 } catch (ObjectStreamException e) {
170 /* order of these Exception catches is important
171 * Deeper sub-classes must be listed before their super classes
173 // TODO: serverListen() add ObjectStreamException handler
174 System.err.println("ObjectStreamException");
176 } catch (IOException e) {
177 // TODO: serverListen() add IOException handler
178 System.err.println("IOException");
180 } catch (ClassNotFoundException e) {
181 // TODO: serverListen() add ClassNotFoundException handler
182 System.err.println("ClassNotFoundException");
189 * Send an unsolicited message to a remote service.
191 * This method is called by the main worker loop if there is a message to
194 * @param message must have its _serviceTarget parameter set
195 * @return true if the message was sent
198 protected boolean serverSend(NetworkMessage message) {
199 boolean result = false;
201 if (message != null) {
202 LastSeenHost host = _serviceToHostMap.get(message.getTarget());
204 InetSocketAddress address = host.address;
205 if (address != null) {
206 message.setSender(_title);
208 byte[] dataSend = NetworkMessage.serialize(message);
209 DatagramPacket packetSend = new DatagramPacket(dataSend, dataSend.length);
210 // set target's remote host address and port
211 packetSend.setAddress(address.getAddress());
212 packetSend.setPort(address.getPort());
214 // acknowledge receipt
215 this.getSocket().send(packetSend);
216 log(Level.FINEST, _title,
217 MessageFormat.format("Sending packet for {0} to {1} ({3}:{4}) from {2}",
221 packetSend.getAddress().getHostAddress(),
226 result = true; // successful
227 } catch (IOException e) {
228 // TODO: serverSend() add IOException handler
233 log(Level.WARNING, _title, MessageFormat.format("Unable to send message for \"{0}\" to unknown target \"{1}\"", message.getIntent(), message.getTarget()));
239 /* XXX: Methods below here all execute on the GUI Event Dispatch Thread */
242 * Clean up after doInBackground() has returned.
244 * This method will run on the Owner Thread so must complete quickly.
247 protected void done() {
248 // TODO: done() implement any clean-up after doInBackground() has returned