KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > gwt > dev > util > NetProxy


1 /*
2  * Copyright 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * 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, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */

16 package com.google.gwt.dev.util;
17
18 import java.io.InputStream JavaDoc;
19 import java.io.OutputStream JavaDoc;
20 import java.io.UnsupportedEncodingException JavaDoc;
21 import java.net.ServerSocket JavaDoc;
22 import java.net.Socket JavaDoc;
23
24 /**
25  * A blind byte-by-byte bi-directional proxy.
26  */

27 public class NetProxy {
28
29   private class ClientToServerProxyConnection extends ProxyConnection {
30     public ClientToServerProxyConnection(Socket JavaDoc clientSideSocket,
31         Socket JavaDoc serverSideSocket) {
32       super(clientSideSocket, serverSideSocket);
33       setName(fromPort + " => " + toPort + " #" + connections);
34     }
35
36     protected void recordBytesTransferred(byte[] bytes, int avail) {
37       addBytesSent(avail, bytes);
38     }
39   }
40
41   private abstract class ProxyConnection extends Thread JavaDoc {
42     private Socket JavaDoc fromSocket;
43     private Socket JavaDoc toSocket;
44
45     public ProxyConnection(Socket JavaDoc fromSocket, Socket JavaDoc toSocket) {
46       this.fromSocket = fromSocket;
47       this.toSocket = toSocket;
48     }
49
50     public void run() {
51       try {
52         InputStream JavaDoc fromSideInput = fromSocket.getInputStream();
53         OutputStream JavaDoc toSideOutput = toSocket.getOutputStream();
54
55         /*
56          * Spin and pass data in one direction.
57          */

58         int avail;
59         byte[] bytes = new byte[32768];
60         while (true) {
61           // Read 'from' side
62
avail = fromSideInput.read(bytes);
63           if (avail > 0) {
64             // Forward to 'to' side
65
toSideOutput.write(bytes, 0, avail);
66             // Accumulate bytes received
67
recordBytesTransferred(bytes, avail);
68           } else if (avail == -1) {
69             break;
70           }
71         }
72       } catch (Throwable JavaDoc e) {
73       } finally {
74         try {
75           fromSocket.close();
76           toSocket.close();
77         } catch (Throwable JavaDoc e) {
78         }
79       }
80     }
81
82     protected abstract void recordBytesTransferred(byte[] bytes, int avail);
83   }
84   private class ServerToClientProxyConnection extends ProxyConnection {
85     public ServerToClientProxyConnection(Socket JavaDoc clientSideSocket,
86         Socket JavaDoc serverSideSocket) {
87       super(serverSideSocket, clientSideSocket);
88       setName(fromPort + " <= " + toPort + " #" + connections);
89     }
90
91     protected void recordBytesTransferred(byte[] bytes, int avail) {
92       addBytesReceived(avail, bytes);
93     }
94   }
95
96   public static void main(String JavaDoc[] args) {
97     if (args.length < 2) {
98       System.out.println("Usage: NetProxy <local-port> <remote-port> [<remote-host>]");
99       return;
100     }
101
102     int localPort = Integer.parseInt(args[0]);
103     int remotePort = Integer.parseInt(args[1]);
104     String JavaDoc remoteHost = args.length < 3 ? "localhost" : args[2];
105     NetProxy netProxy = new NetProxy(localPort, remoteHost, remotePort, true);
106     netProxy.run();
107   }
108
109   private boolean dumpChars;
110   private int fromPort;
111   private String JavaDoc toName;
112   private int toPort;
113   private int bytesSent;
114   private int bytesReceived;
115
116   private int connections;
117
118   private boolean end;
119
120   private long startTime = System.currentTimeMillis();
121
122   public NetProxy(int fromPort, String JavaDoc toName, int toPort, boolean dumpChars) {
123     this.fromPort = fromPort;
124     this.toName = toName;
125     this.toPort = toPort;
126     this.dumpChars = dumpChars;
127   }
128
129   public void end() {
130     end = true;
131   }
132
133   public void run() {
134     try {
135       System.out.println("Time\tBytes Sent\tBytes Received\tTotal Bytes\tHTTP Data");
136       ServerSocket JavaDoc serverSocket = new ServerSocket JavaDoc(fromPort);
137       while (!end) {
138         try {
139           ++connections;
140
141           /*
142            * Listen for and accept the client-initiated connection. Connect to
143            * the real server. Spawn a thread to handle the data shuffling for
144            * newly-created connection.
145            */

146           Socket JavaDoc clientSideSocket = serverSocket.accept();
147           clientSideSocket.setTcpNoDelay(true);
148
149           Socket JavaDoc serverSideSocket = new Socket JavaDoc(toName, toPort);
150           serverSideSocket.setTcpNoDelay(true);
151
152           new ClientToServerProxyConnection(clientSideSocket, serverSideSocket).start();
153           new ServerToClientProxyConnection(clientSideSocket, serverSideSocket).start();
154         } catch (Throwable JavaDoc e) {
155           e.printStackTrace();
156         }
157       }
158     } catch (Throwable JavaDoc e) {
159       // Failed to even be able to listen.
160
e.printStackTrace();
161     }
162   }
163
164   protected int getBytesReceived() {
165     return bytesReceived;
166   }
167
168   protected int getBytesSent() {
169     return bytesSent;
170   }
171
172   private synchronized void addBytesReceived(int byteCount, byte[] bytes) {
173     bytesReceived += byteCount;
174     log(0, byteCount, bytes);
175   }
176
177   private synchronized void addBytesSent(int byteCount, byte[] bytes) {
178     this.bytesSent += byteCount;
179     log(byteCount, 0, bytes);
180   }
181
182   private synchronized void log(int bytesSent, int bytesReceived,
183       byte[] dataBuffer) {
184     System.out.print(System.currentTimeMillis() - startTime);
185     System.out.print("\t");
186     System.out.print(bytesSent);
187     System.out.print("\t");
188     System.out.print(bytesReceived);
189     System.out.print("\t");
190     System.out.print(this.bytesSent + this.bytesReceived);
191     System.out.print("\t");
192     char ch;
193     int avail = (bytesSent != 0 ? bytesSent : bytesReceived);
194     if (dumpChars) {
195       int limit = (avail < 1024 ? avail : 1024);
196       for (int i = 0; i < limit; ++i) {
197         ch = (char) dataBuffer[i];
198         if (ch >= 32 && ch < 128) {
199           System.out.print(ch);
200         } else if (ch == '\n') {
201           System.out.print("\\n");
202         } else if (ch == '\r') {
203           System.out.print("\\r");
204         } else {
205           System.out.print('.');
206         }
207       }
208     } else {
209       // Just read up to the \r\n\r\n.
210
//
211
try {
212         String JavaDoc http = new String JavaDoc(dataBuffer, "UTF-8");
213         int endOfHeaders = http.indexOf("\r\n\r\n");
214         if (endOfHeaders != -1 && http.indexOf("HTTP") != -1) {
215           http = http.replaceAll("\\r", "");
216           http = http.replaceAll("\\n", "\n\t\t\t\t");
217           System.out.print(http.substring(0, endOfHeaders));
218         } else {
219           System.out.print("(data)");
220         }
221       } catch (UnsupportedEncodingException JavaDoc e) {
222         e.printStackTrace();
223       }
224     }
225
226     System.out.println();
227   }
228 }
229
Popular Tags