KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > samples > transport > tcp > TCPListener


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package samples.transport.tcp;
18
19 import org.apache.axis.AxisEngine;
20 import org.apache.axis.AxisFault;
21 import org.apache.axis.Message;
22 import org.apache.axis.MessageContext;
23 import org.apache.axis.components.logger.LogFactory;
24 import org.apache.axis.configuration.XMLStringProvider;
25 import org.apache.axis.deployment.wsdd.WSDDConstants;
26 import org.apache.axis.server.AxisServer;
27 import org.apache.axis.utils.Options;
28 import org.apache.commons.logging.Log;
29
30 import java.io.BufferedOutputStream JavaDoc;
31 import java.io.ByteArrayInputStream JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.io.InputStream JavaDoc;
34 import java.io.OutputStream JavaDoc;
35 import java.net.MalformedURLException JavaDoc;
36 import java.net.ServerSocket JavaDoc;
37 import java.net.Socket JavaDoc;
38 import java.net.URL JavaDoc;
39
40 /**
41  * Listen for incoming socket connections on the specified socket. Take
42  * incoming messages and dispatch them.
43  *
44  * @author Rob Jellinghaus (robj@unrealities.com)
45  * @author Doug Davis (dug@us.ibm.com)
46  */

47 public class TCPListener implements Runnable JavaDoc {
48     static Log log =
49             LogFactory.getLog(TCPSender.class.getName());
50
51     // These have default values.
52
private String JavaDoc transportName = "TCPTransport";
53
54     private static final String JavaDoc AXIS_ENGINE = "AxisEngine" ;
55
56     private int port;
57     private ServerSocket JavaDoc srvSocket;
58
59     private AxisEngine engine = null ;
60
61     // becomes true when we want to quit
62
private boolean done = false;
63
64     static final String JavaDoc wsdd =
65             "<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
66                   "xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
67             " <transport name=\"tcp\" pivot=\"java:samples.transport.tcp.TCPSender\"/>\n" +
68             " <service name=\"" + WSDDConstants.URI_WSDD + "\" provider=\"java:MSG\">\n" +
69             " <parameter name=\"allowedMethods\" value=\"AdminService\"/>\n" +
70             " <parameter name=\"className\" value=\"org.apache.axis.utils.Admin\"/>\n" +
71             " </service>\n" +
72             "</deployment>";
73
74     public static void main (String JavaDoc args[]) {
75         new TCPListener(args).run();
76     }
77
78     public TCPListener (String JavaDoc[] args) {
79         // look for -p, -d arguments
80
try {
81             Options options = new Options(args);
82             port = new URL JavaDoc(options.getURL()).getPort();
83         } catch (MalformedURLException JavaDoc ex) {
84             log.error("Hosed URL: "+ex);
85             System.exit(1);
86         }
87
88         try {
89             srvSocket = new ServerSocket JavaDoc(port);
90         } catch (IOException JavaDoc ex) {
91             log.error("Can't create server socket on port "+port);
92             System.exit(1);
93         }
94
95         log.info("TCPListener is listening on port "+port+".");
96     }
97
98     public void run () {
99         if (srvSocket == null) {
100             return;
101         }
102
103         Socket JavaDoc sock;
104         while (!done) {
105             try {
106                 sock = srvSocket.accept();
107                 log.info("TCPListener received new connection: "+sock);
108                 new Thread JavaDoc(new SocketHandler(sock)).start();
109             } catch (IOException JavaDoc ex) {
110                 /** stop complaining about this! it seems to happen on quit,
111                     and is not worth mentioning. unless I am confused. -- RobJ
112                  */

113                 log.debug("Got IOException on srvSocket.accept: "+ex);
114             }
115         }
116     }
117
118
119     public class SocketHandler implements Runnable JavaDoc {
120         private Socket JavaDoc socket;
121         public SocketHandler (Socket JavaDoc socket) {
122             this.socket = socket;
123         }
124         public void run () {
125             // get the input stream
126
if ( engine == null ) {
127                 XMLStringProvider provider = new XMLStringProvider(wsdd);
128                 engine = new AxisServer(provider);
129                 engine.init();
130             }
131
132             /* Place the Request message in the MessagContext object - notice */
133             /* that we just leave it as a 'ServletRequest' object and let the */
134             /* Message processing routine convert it - we don't do it since we */
135             /* don't know how it's going to be used - perhaps it might not */
136             /* even need to be parsed. */
137             /*******************************************************************/
138             MessageContext msgContext = new MessageContext(engine);
139
140             InputStream JavaDoc inp;
141             try {
142                 inp = socket.getInputStream();
143             } catch (IOException JavaDoc ex) {
144                 log.error("Couldn't get input stream from "+socket);
145                 return;
146             }
147
148             // ROBJ 911
149
// the plain ol' inputstream seems to hang in the SAX parse..... WHY?????
150
// because there is no content length!
151
//Message msg = new Message( nbbinp, "InputStream" );
152
Message msg = null;
153             try {
154                 StringBuffer JavaDoc line = new StringBuffer JavaDoc();
155                 int b = 0;
156                 while ((b = inp.read()) != '\r') {
157                     line.append((char)b);
158                 }
159                 // got to '\r', skip it and '\n'
160
if (inp.read() != '\n') {
161                     log.error("Length line "+line+" was not terminated with \r\n");
162                     return;
163                 }
164
165                 // TEST SUPPORT ONLY
166
// If the line says "ping", then respond "\n".
167
// If the line says "quit", then respond "\n" and exit.
168
if (line.toString().equals("ping")) {
169                     socket.getOutputStream().write(new String JavaDoc("\n").getBytes());
170                     return;
171                 } else if (line.toString().equals("quit")) {
172                     // peacefully die
173
socket.getOutputStream().write(new String JavaDoc("\n").getBytes());
174                     socket.close();
175                     // The following appears to deadlock. It will get cleaned
176
// up on exit anyway...
177
// srvSocket.close();
178
log.error("AxisListener quitting.");
179                     System.exit(0);
180                 }
181
182
183                 // OK, assume it is content length
184
int len = Integer.parseInt(line.toString());
185                 // read that many bytes into ByteArrayInputStream...
186

187                 // experiment, doesn't work:
188
// NonBlockingBufferedInputStream nbbinp = new NonBlockingBufferedInputStream();
189
// nbbinp.setContentLength(len);
190
// nbbinp.setInputStream(inp);
191
// msg = new Message(nbbinp, "InputStream");
192

193                 byte[] mBytes = new byte[len];
194                 inp.read(mBytes);
195                 msg = new Message(new ByteArrayInputStream JavaDoc(mBytes));
196             } catch (IOException JavaDoc ex) {
197                 log.error("Couldn't read from socket input stream: "+ex);
198                 return;
199             }
200
201
202             /* Set the request(incoming) message field in the context */
203             /**********************************************************/
204             msgContext.setRequestMessage( msg );
205
206             /* Set the Transport Specific Request/Response chains IDs */
207             /******************************************************/
208             msgContext.setTransportName(transportName);
209
210             try {
211                 /* Invoke the Axis engine... */
212                 /*****************************/
213                 engine.invoke( msgContext );
214             }
215             catch( Exception JavaDoc e ) {
216                 AxisFault fault = AxisFault.makeFault(e);
217                 msgContext.setResponseMessage( new Message(fault) );
218             }
219
220             /* Send it back along the wire... */
221             /***********************************/
222             msg = msgContext.getResponseMessage();
223             String JavaDoc response = null;
224             if (msg == null) {
225                 response="No data";
226             } else {
227                 try {
228                     response = (String JavaDoc) msg.getSOAPPartAsString();
229                 } catch (AxisFault fault) {
230                     msg = new Message(fault);
231                     try {
232                         response = (String JavaDoc)msg.getSOAPPartAsString();
233                     } catch (AxisFault fault2) {
234                         response = fault2.dumpToString();
235                     }
236                 }
237             }
238
239             try {
240                 OutputStream JavaDoc buf = new BufferedOutputStream JavaDoc(socket.getOutputStream());
241                 // this should probably specify UTF-8, but for now, for Java interop,
242
// use default encoding
243
buf.write(response.getBytes());
244                 buf.close();
245             } catch (IOException JavaDoc ex) {
246                 log.error("Can't write response to socket "+port+", response is: "+response);
247             }
248         }
249     }
250 }
251
252
253
Popular Tags