KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > rero > net > SocketConnection


1 package rero.net;
2
3 import rero.net.SocketEvent;
4 import rero.net.interfaces.SocketDataListener;
5 import rero.net.interfaces.SocketStatusListener;
6
7 import java.io.*;
8 import java.net.*;
9 import java.util.LinkedList JavaDoc;
10 import java.util.ListIterator JavaDoc;
11
12 import javax.net.ssl.*;
13
14 import rero.util.*;
15
16 import rero.config.*;
17
18 public class SocketConnection implements Runnable JavaDoc, ClientStateListener
19 {
20    protected Socket aSocket;
21    protected Thread JavaDoc readThread;
22    protected PrintStream aSocketOutput;
23    protected BufferedReader aSocketInput;
24    protected long delay; // number of ms to wait before trying to connect.
25

26    public void propertyChanged(String JavaDoc property, String JavaDoc value)
27    {
28       try
29       {
30          if (aSocketInput != null && aSocket.isConnected())
31          {
32             aSocketInput = new BufferedReader(ClientState.getProperInputStream(aSocket.getInputStream()));
33             aSocketOutput = ClientState.getProperPrintStream(aSocket.getOutputStream());
34          }
35       }
36       catch (Exception JavaDoc ex)
37       {
38          System.out.println("Unable to switch encodings...");
39          ex.printStackTrace();
40       }
41    }
42
43    public void println(String JavaDoc message)
44    {
45       try
46       {
47          aSocketOutput.println(message);
48          aSocketOutput.flush();
49       }
50       catch (Exception JavaDoc ex)
51       {
52          ex.printStackTrace();
53       }
54    }
55
56    public void disconnect()
57    {
58       if (aSocket != null && aSocket.isConnected())
59       {
60          try
61          {
62             if (!aSocket.isOutputShutdown()) aSocket.shutdownOutput();
63             if (!aSocket.isInputShutdown()) aSocket.shutdownInput();
64             aSocket.close();
65          }
66          catch (Exception JavaDoc ex)
67          {
68             // pretty safe to ignore, we may just make it so this exception goes no where eventually //
69
ex.printStackTrace();
70          }
71          aSocket = null;
72       }
73    }
74
75    public void connect(String JavaDoc host, int port)
76    {
77       connect(host, port, 0, null, false);
78    }
79
80    public void connect(String JavaDoc host, int port, long _delay, String JavaDoc password, boolean secure)
81    {
82       delay = _delay;
83
84       if (readThread != null)
85       {
86          try
87          {
88             disconnect();
89
90             readThread.interrupt(); // gotta stop the stupid thing somehow.
91

92             readThread.join(1 * 1000); // wait for the disconnection to actually
93
// happen. This may kill the responsiveness
94
// of the application. Something to watch
95
// out for.
96
}
97          catch (Exception JavaDoc ex)
98          {
99             ex.printStackTrace();
100          }
101       }
102
103       getSocketInformation().hostname = host;
104       getSocketInformation().port = port;
105       getSocketInformation().isSecure = secure;
106       getSocketInformation().password = password;
107       getSocketInformation().network = "Unknown";
108
109 // System.out.println(getSocketInformation().hostname + ", " + getSocketInformation().port + ", " + getSocketInformation().isSecure + ", " + getSocketInformation().password);
110

111       readThread = new Thread JavaDoc(this);
112       readThread.setName("Socket Read Thread for: " + host);
113       readThread.start();
114    }
115
116    public void run()
117    {
118       aSocketInput = null;
119       aSocketOutput = null;
120
121       try
122       {
123          if (delay > 0) Thread.sleep(delay);
124       }
125       catch (Exception JavaDoc ex)
126       {
127          ex.printStackTrace();
128          return;
129       }
130
131       //
132
// Attempt to connect...
133
//
134
try
135       {
136          // once config system is in place have an option to jack up socket time outs.
137

138          if (getSocketInformation().isSecure) /* ratdog - you owe me one you bastard! */
139          {
140             aSocket = (new SecureSocket(getSocketInformation().hostname, getSocketInformation().port)).getSocket();
141          }
142          else
143          {
144             aSocket = new Socket(getSocketInformation().hostname, getSocketInformation().port);
145          }
146
147          aSocket.setSoLinger(true, 5); // 5 second socket disconnect linger time to flush data.
148
aSocket.setTcpNoDelay(true); // we'll try this out, it might suck?
149
aSocket.setSoTimeout(5 * 60 * 1000); // timeout after half an hour, why not eh?
150

151          /* setup our streams for input and output */
152
153          aSocketOutput = ClientState.getProperPrintStream(aSocket.getOutputStream());
154          aSocketInput = new BufferedReader(ClientState.getProperInputStream(aSocket.getInputStream()));
155       }
156       catch (UnknownHostException ex1)
157       {
158          fireStatusEvent("unable to resolve hostname", false);
159          return;
160       }
161       catch (Exception JavaDoc ex2)
162       {
163          if (Thread.currentThread() != readThread) // check to make sure this isn't a left over connection attempt.
164
{
165             return;
166          }
167
168          fireStatusEvent(ex2.getMessage(), false);
169          return;
170       }
171     
172       if (aSocket != null)
173       {
174          fireStatusEvent("success", true);
175       }
176           
177       /* we are connected, let's loop, read messages, and fire events... the good life */
178
179       String JavaDoc data = null;
180
181       do
182       {
183          try
184          {
185             data = aSocketInput.readLine();
186
187             if (data != null)
188                fireReadEvent(data);
189          }
190          catch (SocketException ex1)
191          {
192             fireStatusEvent(ex1.getMessage(), false);
193             shutdownSocket();
194             return;
195          }
196          catch (IOException ex2)
197          {
198             fireStatusEvent(ex2.getMessage(), false);
199             shutdownSocket();
200             return;
201          }
202          catch (Exception JavaDoc ex3)
203          {
204             if (aSocket == null || !aSocket.isConnected())
205             {
206                fireStatusEvent(ex3.getMessage(), false);
207                shutdownSocket();
208                return;
209             }
210
211             ex3.printStackTrace();
212          }
213       }
214       while (aSocket != null && aSocket.isConnected() && data != null);
215
216       fireStatusEvent("disconnected.", false);
217       shutdownSocket();
218    }
219
220    private void shutdownSocket()
221    {
222       try
223       {
224          if (aSocketInput != null) { aSocketInput.close(); }
225          if (aSocketOutput != null) { aSocketOutput.close(); }
226          if (aSocket != null) { aSocket.close(); }
227       }
228       catch (Exception JavaDoc ex) { ex.printStackTrace(); }
229    }
230
231    //
232
// data structure
233
//
234
protected SocketInformation connectionInformation;
235
236    public SocketInformation getSocketInformation()
237    {
238       return connectionInformation;
239    }
240
241    public SocketConnection()
242    {
243       connectionInformation = new SocketInformation();
244
245       event.socket = this;
246       event.data = connectionInformation;
247
248       ClientState.getClientState().addClientStateListener("client.encoding", this);
249
250       if (listener2 == null)
251       {
252          listener2 = new ClientStateListener() {
253              public void propertyChanged(String JavaDoc key, String JavaDoc value)
254              {
255                 stripcodes = ClientState.getClientState().isOption("client.stripcodes", ClientDefaults.client_stripcodes);
256              }
257          };
258
259          listener2.propertyChanged(null, null);
260          ClientState.getClientState().addClientStateListener("client.stripcodes", listener2);
261       }
262    }
263
264    private static boolean stripcodes;
265    private static ClientStateListener listener2 = null;
266
267    LinkedList JavaDoc connectDisconnectListeners = new LinkedList JavaDoc();
268    LinkedList JavaDoc messageReadListeners = new LinkedList JavaDoc();
269
270    SocketEvent event = new SocketEvent();
271
272    public void removeSocketStatusListener(SocketStatusListener l)
273    {
274       connectDisconnectListeners.remove(l);
275    }
276
277    public void removeSocketDataListener(SocketDataListener l)
278    {
279       messageReadListeners.remove(l);
280    }
281
282    public void addSocketStatusListener(SocketStatusListener l)
283    {
284       connectDisconnectListeners.addFirst(l);
285    }
286
287    public void addSocketDataListener(SocketDataListener l)
288    {
289       messageReadListeners.addFirst(l);
290    }
291
292    public void fireStatusEvent(String JavaDoc message, boolean isConnected)
293    {
294       getSocketInformation().isConnected = isConnected;
295
296       event.message = message;
297       event.valid = true;
298
299       ListIterator JavaDoc en = connectDisconnectListeners.listIterator();
300       while (en.hasNext() && event.valid)
301       {
302          SocketStatusListener temp = (SocketStatusListener)en.next();
303          temp.socketStatusChanged(event);
304       }
305    }
306
307    public void fireReadEvent(String JavaDoc message)
308    {
309       if (stripcodes)
310       {
311          message = ClientUtils.strip(message);
312       }
313
314       event.message = message;
315       event.valid = true;
316
317       ListIterator JavaDoc en = messageReadListeners.listIterator();
318       while (en.hasNext() && event.valid)
319       {
320          SocketDataListener temp = (SocketDataListener)en.next();
321          temp.socketDataRead(event);
322       }
323    }
324 }
325
Popular Tags