Implemented TCP streams for object serialization
[WeStealzYourDataz.git] / src / uk / ac / ntu / n0521366 / wsyd / libs / net / NetworkServerTCP.java
1 /*
2  * The MIT License
3  *
4  * Copyright 2015 TJ <hacker@iam.tj>.
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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
22  * THE SOFTWARE.
23  */
24 package uk.ac.ntu.n0521366.wsyd.libs.net;
25
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;
35
36 /**
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.
39  *
40  * @see NetworkServerAbstract
41  * @author TJ <hacker@iam.tj>
42  */
43 public class NetworkServerTCP extends NetworkServerAbstract {
44     
45     ServerSocket _serverSocket;
46     
47     NetworkStreamManager _streamManager;
48
49      /**
50      * Construct the server with a Logger.
51      * 
52      * No socket is opened.
53      * 
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
57      * @param manager
58      * @param logger An instance of Logger to be used by all objects of this class
59      */
60     public NetworkServerTCP(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap, NetworkStreamManager manager, Logger logger) {
61         super(socketAddress, title, serviceToHostMap, logger);
62         this._streamManager = manager;
63     }
64
65     /**
66      * Construct the server without a Logger.
67      * 
68      * No socket is opened.
69      * 
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
73      * @param manager
74      */
75     public NetworkServerTCP(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap, NetworkStreamManager manager) {
76         super(socketAddress, title, serviceToHostMap);
77         this._streamManager = manager;
78     }
79     
80     /**
81      * Open the socket ready for accepting connections.
82      * 
83      * It should also set a reasonable socket timeout with a call to setSoTimeout()
84      * 
85      * @throws SocketException 
86      */
87     @Override
88     public  void serverOpen() throws SocketException {
89         try {
90             _serverSocket = new ServerSocket(_socketAddress.getPort(), 50, _socketAddress.getAddress());
91         } catch (IOException ex) {
92             throw new SocketException(ex.getMessage());
93         }
94         _serverSocket.setSoTimeout(100);
95         
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());
101         }
102         //log(Level.FINEST, _title, MessageFormat.format("Connection from {0}:{1}", _socketAddress.getAddress().getCanonicalHostName(), Integer.toString(_socketAddress.getPort())));
103         // TODO: Complete this implementation
104     }
105     
106     /**
107      * Send an unsolicited message to a remote service.
108      * 
109      * This method is called by the main worker loop if there is a message to
110      * be sent.
111      * 
112      * @param message must have its _serviceTarget parameter set
113      * @return true if the message was sent
114      */
115     @Override
116     protected boolean serverSend(NetworkMessage message) {
117         boolean result = false;
118         
119         return result;
120     }
121
122     /**
123      * Close the socket.
124      * 
125      * @throws SocketException
126      */
127     @Override
128     public void serverClose() throws SocketException {
129         if (this._serverSocket != null)
130             try {
131                 this._serverSocket.close();
132         } catch (IOException ex) {
133             throw new SocketException(ex.getMessage());
134         }
135     }
136     
137     /**
138      * Accept connection from remote hosts.
139      * 
140      * This method should wait for a single incoming connection.
141      * 
142      * @return true if the server should continue listening
143      */
144     @Override
145     public boolean serverListen() {
146         boolean result = false;
147         
148         try {
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())));
154         }
155         catch (SocketTimeoutException e) {
156             //Nothing to be done
157         }
158         catch (IOException e) {
159             // Nothing to be done
160             System.err.println("Incoming connection caused exception...");
161         }
162        
163         return false;
164     }
165
166     /* XXX: Methods below here all execute on the GUI Event Dispatch Thread */
167     
168     /**
169      * Clean up after doInBackground() has returned.
170      * 
171      * This method will run on the GUI Event Dispatch Thread so must complete quickly.
172      */
173     @Override
174     protected  void done() {
175         
176     }
177 }