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.io.IOException;
27 import java.net.InetSocketAddress;
28 import java.net.ServerSocket;
29 import java.net.Socket;
30 import java.net.SocketException;
31 import java.net.SocketTimeoutException;
32 import java.text.MessageFormat;
33 import java.util.logging.Level;
34 import java.util.logging.Logger;
37 * Dual-use multithreading network TCP server that can be used stand-alone
38 * or in a Swing GUI application as a background worker thread.
40 * @see NetworkServerAbstract
41 * @author TJ <hacker@iam.tj>
43 public class NetworkServerTCP extends NetworkServerAbstract {
45 ServerSocket _serverSocket;
47 NetworkStreamManager _streamManager;
50 * Construct the server with a Logger.
52 * No socket is opened.
54 * @param socketAddress The socket to listen on
55 * @param title source identifier for use in log messages and sent NetworkMessage objects
56 * @param serviceToHostMap the map object used for host <> InetSocketAddress lookups
58 * @param logger An instance of Logger to be used by all objects of this class
60 public NetworkServerTCP(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap, NetworkStreamManager manager, Logger logger) {
61 super(socketAddress, title, serviceToHostMap, logger);
62 this._streamManager = manager;
66 * Construct the server without a Logger.
68 * No socket is opened.
70 * @param socketAddress The socket to listen on
71 * @param title source identifier for use in log messages and sent NetworkMessage objects
72 * @param serviceToHostMap the map object used for host <> InetSocketAddress lookups
75 public NetworkServerTCP(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap, NetworkStreamManager manager) {
76 super(socketAddress, title, serviceToHostMap);
77 this._streamManager = manager;
81 * Open the socket ready for accepting connections.
83 * It should also set a reasonable socket timeout with a call to setSoTimeout()
85 * @throws SocketException
88 public void serverOpen() throws SocketException {
90 _serverSocket = new ServerSocket(_socketAddress.getPort(), 50, _socketAddress.getAddress());
91 } catch (IOException ex) {
92 throw new SocketException(ex.getMessage());
94 _serverSocket.setSoTimeout(100);
96 if (_socketAddress.getPort() == Network.PORTS_EPHEMERAL) {
97 // reflect the actual port in use if an ephermal port was requested
98 InetSocketAddress actualSA = (InetSocketAddress)_serverSocket.getLocalSocketAddress();
99 _socketAddress.setAddress(actualSA.getAddress());
100 _socketAddress.setPort(actualSA.getPort());
102 //log(Level.FINEST, _title, MessageFormat.format("Connection from {0}:{1}", _socketAddress.getAddress().getCanonicalHostName(), Integer.toString(_socketAddress.getPort())));
103 // TODO: Complete this implementation
107 * Send an unsolicited message to a remote service.
109 * This method is called by the main worker loop if there is a message to
112 * @param message must have its _serviceTarget parameter set
113 * @return true if the message was sent
116 protected boolean serverSend(NetworkMessage message) {
117 boolean result = false;
125 * @throws SocketException
128 public void serverClose() throws SocketException {
129 if (this._serverSocket != null)
131 this._serverSocket.close();
132 } catch (IOException ex) {
133 throw new SocketException(ex.getMessage());
138 * Accept connection from remote hosts.
140 * This method should wait for a single incoming connection.
142 * @return true if the server should continue listening
145 public boolean serverListen() {
146 boolean result = false;
149 //System.err.println("Before");
150 Socket connectionSocket = _serverSocket.accept();
151 NetworkStream newStream = new NetworkStream(connectionSocket, _streamManager);
152 _streamManager.addStream(0, newStream);
153 log(Level.INFO, _title, MessageFormat.format("Incoming connection from {0}:{1}", connectionSocket.getInetAddress().getCanonicalHostName(), Integer.toString(connectionSocket.getPort())));
155 catch (SocketTimeoutException e) {
158 catch (IOException e) {
159 // Nothing to be done
160 System.err.println("Incoming connection caused exception...");
166 /* XXX: Methods below here all execute on the GUI Event Dispatch Thread */
169 * Clean up after doInBackground() has returned.
171 * This method will run on the GUI Event Dispatch Thread so must complete quickly.
174 protected void done() {