├── .gitignore ├── LICENSE ├── README.md ├── https ├── 1..txt ├── 2..txt └── 3..txt ├── source ├── ProxyHttpServer.jar ├── cmd-console.png ├── http-page.png ├── proxy.png ├── run.bat └── run.png └── src ├── nicelee ├── config │ ├── ConfigReader.java │ └── model │ │ └── Config.java └── http │ ├── MainApplication.java │ ├── core │ ├── SocketServer.java │ ├── file │ │ └── transfer │ │ │ ├── HttpDataTransfer.java │ │ │ ├── HttpHeaderTransfer.java │ │ │ └── common │ │ │ └── CommonResponse.java │ └── runnable │ │ ├── ProxyDealer.java │ │ ├── SocketDealer.java │ │ └── SocketMonitor.java │ ├── model │ ├── HttpRequest.java │ └── HttpResponse.java │ ├── resource │ └── HttpResource.java │ └── util │ └── StreamReader.java └── resources └── console.display /.gitignore: -------------------------------------------------------------------------------- 1 | /.project 2 | /.settings 3 | /.classpath 4 | */download 5 | *.zip 6 | *.log 7 | *.config 8 | /bin 9 | /target 10 | /src/nicelee/http/sample 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ProxyHttpServer 2 | 基于Java 原生TCPSocket实现的小型HttpProxy代理服务器Demo,能够代理http。 3 | 文件大小约1M大小哦。 4 | 5 | 6 | ## 配置 7 | 配置从同级目录下的```app.config```中加载。 8 | 9 | | 属性 | 值 | 默认值 | 10 | | ------------- | ------------- |------------- | 11 | | nicelee.server.mode | 运行模式:0 FileHttp/ 1 ProxyHttp | 1 | 12 | | nicelee.server.port | 服务器监听端口 | 7777 | 13 | | nicelee.server.fixedPoolSize |目前使用fixedThreadPool管理Socket处理线程,可以看作是最大TCP并发连接数 | 30 | 14 | | nicelee.server.socketTimeout | 最大socket连接时长,单位ms(针对TCP端口被长连接长时间占用) | 120000 | 15 | | nicelee.server.source | 目的文件目录 | . | 16 | 17 | ## 简介 18 | * 运行 19 | 运行```run.bat```即可 20 | ![](https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/master/source/run.png) 21 | 22 | 后台界面如下: 23 | ![](https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/master/source/cmd-console.png) 24 | 25 | * 功能概览 26 | 客户端代理访问http页面正常(https代理功能实现中哦...) 27 | ![](https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/master/source/http-page.png) 28 | 29 | 目的服务器端Headers如下,其中```123.123.123.123```为伪IP 30 | ![](https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/master/source/proxy.png) 31 | 32 | 33 | ## 其它 34 | * **下载地址**: [https://github.com/nICEnnnnnnnLee/ProxyHttpServer/releases](https://github.com/nICEnnnnnnnLee/ProxyHttpServer/releases) 35 | * **GitHub**: [https://github.com/nICEnnnnnnnLee/ProxyHttpServer](https://github.com/nICEnnnnnnnLee/ProxyHttpServer) 36 | * **Gitee码云**: [https://gitee.com/NiceLeee/ProxyHttpServer](https://gitee.com/NiceLeee/ProxyHttpServer) 37 | * **LICENSE**: [Apache License v2.0](https://www.apache.org/licenses/LICENSE-2.0.html) 38 | 39 | 40 | ## 更新日志 41 | * v1.2(当前版本) 42 | * 整合FileHttpServer/ProxyHttpServer 43 | * 添加了对Headers头部中If-Modified-Since/Last-Modified的解析 44 | * v1.1 45 | * 支持Https代理 46 | * 修正了一个headers的解析问题, 该问题会导致不限于Referer标签值获取失败等问题 47 | * 修正了某些bug, 该bug会导致post访问时代理失败 48 | * 与客户端/服务器端输入输出全部采用字节流 49 | * v1.0 50 | * 支持http代理(已完成,(づ ̄3 ̄)づ╭❤~) 51 | * 目前仅作中转,尚未支持https的代理,待继续完成.. ( ̄ε(# ̄)☆╰╮o( ̄皿 ̄///) 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /https/1..txt: -------------------------------------------------------------------------------- 1 | CONNECT www.baidu.com:443 HTTP/1.1 2 | Host: www.baidu.com:443 3 | Connection: keep-alive 4 | User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0 5 | 6 | A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below. 7 | 8 | Version: 3.3 (TLS/1.2) 9 | Random: 35 1A 82 B6 64 DF B5 B8 E7 5A 0C 17 E9 8F F2 FF 46 CF EE D3 3B 47 E0 33 45 30 62 BF 76 89 46 72 10 | "Time": 2067/1/11 21:55:01 11 | SessionID: 65 EF B5 E9 7D 16 60 06 87 0A 9C F4 CA AE 0F 64 46 A9 15 12 AC F9 84 F6 F2 E5 20 08 11 F9 D9 9D 12 | Extensions: 13 | 0x8a8a empty 14 | renegotiation_info 00 15 | server_name www.baidu.com 16 | extended_master_secret empty 17 | SessionTicket CD 49 BA A5 F0 8C 2C FC 7F D9 89 0E 6C 30 37 1C 19 9C 9A 9F FA 20 63 12 50 F3 CC C0 48 79 EA 71 31 EB DE 31 4B 93 4C CA C6 20 C3 AF DD 98 17 6E 62 09 08 E3 EF 07 86 9D 8A 1C 96 70 47 83 61 B0 71 C6 93 2F 1D 13 29 BF 67 D7 C1 AE E6 EC 46 AB BB 4B 55 22 49 70 A5 A0 A2 C7 7E 81 39 CE 0D EE C7 CA 69 6B 6B 2D B7 E5 37 93 1E C5 3A 2E 02 0B B5 FA 10 34 DA 40 E1 CA E0 20 86 EC 34 98 7A C3 A5 15 73 FC 76 48 A1 DD 5B 04 4A 3D F5 C5 9A C1 39 A8 4A 33 E6 34 AF 98 CC BE 35 65 4E 9B 35 71 18 | signature_algs sha256_ecdsa, Unknown[0x8]_Unknown[0x4], sha256_rsa, sha384_ecdsa, Unknown[0x8]_Unknown[0x5], sha384_rsa, Unknown[0x8]_Unknown[0x6], sha512_rsa, sha1_rsa 19 | status_request OCSP - Implicit Responder 20 | SignedCertTimestamp (RFC6962) empty 21 | ALPN h2, http/1.1 22 | channel_id(GoogleDraft) empty 23 | ec_point_formats uncompressed [0x0] 24 | elliptic_curves unknown [0x1A1A), unknown [0x1D), secp256r1 [0x17], secp384r1 [0x18] 25 | 0xbaba 00 26 | padding 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 | Ciphers: 28 | [3A3A] Unrecognized cipher - See http://www.iana.org/assignments/tls-parameters/ 29 | [C02B] TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 30 | [C02F] TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 31 | [C02C] TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 32 | [C030] TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 33 | [CCA9] TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 34 | [CCA8] TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 35 | [C013] TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA 36 | [C014] TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA 37 | [009C] TLS_RSA_WITH_AES_128_GCM_SHA256 38 | [009D] TLS_RSA_WITH_AES_256_GCM_SHA384 39 | [002F] TLS_RSA_AES_128_SHA 40 | [0035] TLS_RSA_AES_256_SHA 41 | [000A] SSL_RSA_WITH_3DES_EDE_SHA 42 | 43 | Compression: 44 | [00] NO_COMPRESSION 45 | 46 | -------------------------------------------------------------------------------------------------- 47 | HTTP/1.1 200 Connection Established 48 | FiddlerGateway: Direct 49 | StartTime: 17:12:51.541 50 | Connection: close 51 | 52 | Encrypted HTTPS traffic flows through this CONNECT tunnel. HTTPS Decryption is enabled in Fiddler, so decrypted sessions running in this tunnel will be shown in the Web Sessions list. 53 | 54 | Secure Protocol: Tls12 55 | Cipher: Aes128 128bits 56 | Hash Algorithm: Sha256 ?bits 57 | Key Exchange: ECDHE_RSA (0xae06) 256bits 58 | 59 | == Server Certificate ========== 60 | [Subject] 61 | CN=baidu.com, O="Beijing Baidu Netcom Science Technology Co., Ltd", OU=service operation department, L=beijing, S=beijing, C=CN 62 | 63 | [Issuer] 64 | CN=GlobalSign Organization Validation CA - SHA256 - G2, O=GlobalSign nv-sa, C=BE 65 | 66 | [Serial Number] 67 | 21ED2CC2F1092C666B15E527 68 | 69 | [Not Before] 70 | 2018/4/3 11:26:03 71 | 72 | [Not After] 73 | 2019/5/26 13:31:02 74 | 75 | [Thumbprint] 76 | D6AAF8CFA0E0236547FC2A894F895EC94724A60D 77 | 78 | [SubjectAltNames] 79 | baidu.com, baifubao.com, www.baidu.cn, www.baidu.com.cn, mct.y.nuomi.com, baifae.com, apollo.auto, *.baidu.com, *.baifubao.com, *.baidustatic.com, *.bdstatic.com, *.bdimg.com, *.hao123.com, *.nuomi.com, *.chuanke.com, *.trustgo.com, *.bce.baidu.com, *.eyun.baidu.com, *.map.baidu.com, *.mbd.baidu.com, *.fanyi.baidu.com, *.baidubce.com, *.mipcdn.com, *.news.baidu.com, *.baidupcs.com, *.aipage.com, *.aipage.cn, *.bcehost.com, *.safe.baidu.com, *.im.baidu.com, *.ssl2.duapps.com, *.baifae.com, *.baiducontent.com, *.dlnel.com, *.dlnel.org, *.dueros.baidu.com, *.su.baidu.com, *.91.com, *.hao123.baidu.com, *.apollo.auto, *.xueshu.baidu.com, *.bj.baidubce.com, *.gz.baidubce.com, click.hm.baidu.com, log.hm.baidu.com, cm.pos.baidu.com, wn.pos.baidu.com, update.pan.baidu.com 80 | -------------------------------------------------------------------------------- /https/2..txt: -------------------------------------------------------------------------------- 1 | CONNECT www.baidu.com:443 HTTP/1.1 2 | Host: www.baidu.com:443 3 | Connection: keep-alive 4 | User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0 5 | 6 | A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below. 7 | 8 | Version: 3.3 (TLS/1.2) 9 | Random: 59 80 49 67 EB 3A D9 94 AE 41 0C 2E 0B 38 2E 35 26 5F 35 92 09 75 B7 70 60 B9 B1 8C AA B8 91 2D 10 | "Time": 2024/11/29 16:50:33 11 | SessionID: 65 EF B5 E9 7D 16 60 06 87 0A 9C F4 CA AE 0F 64 46 A9 15 12 AC F9 84 F6 F2 E5 20 08 11 F9 D9 9D 12 | Extensions: 13 | 0x4a4a empty 14 | renegotiation_info 00 15 | server_name www.baidu.com 16 | extended_master_secret empty 17 | SessionTicket CD 49 BA A5 F0 8C 2C FC 7F D9 89 0E 6C 30 37 1C 19 9C 9A 9F FA 20 63 12 50 F3 CC C0 48 79 EA 71 31 EB DE 31 4B 93 4C CA C6 20 C3 AF DD 98 17 6E 62 09 08 E3 EF 07 86 9D 8A 1C 96 70 47 83 61 B0 71 C6 93 2F 1D 13 29 BF 67 D7 C1 AE E6 EC 46 AB BB 4B 55 22 49 70 A5 A0 A2 C7 7E 81 39 CE 0D EE C7 CA 69 6B 6B 2D B7 E5 37 93 1E C5 3A 2E 02 0B B5 FA 10 34 DA 40 E1 CA E0 20 86 EC 34 98 7A C3 A5 15 73 FC 76 48 A1 DD 5B 04 4A 3D F5 C5 9A C1 39 A8 4A 33 E6 34 AF 98 CC BE 35 65 4E 9B 35 71 18 | signature_algs sha256_ecdsa, Unknown[0x8]_Unknown[0x4], sha256_rsa, sha384_ecdsa, Unknown[0x8]_Unknown[0x5], sha384_rsa, Unknown[0x8]_Unknown[0x6], sha512_rsa, sha1_rsa 19 | status_request OCSP - Implicit Responder 20 | SignedCertTimestamp (RFC6962) empty 21 | ALPN h2, http/1.1 22 | channel_id(GoogleDraft) empty 23 | ec_point_formats uncompressed [0x0] 24 | elliptic_curves unknown [0x8A8A), unknown [0x1D), secp256r1 [0x17], secp384r1 [0x18] 25 | 0x6a6a 00 26 | padding 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 | Ciphers: 28 | [5A5A] Unrecognized cipher - See http://www.iana.org/assignments/tls-parameters/ 29 | [C02B] TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 30 | [C02F] TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 31 | [C02C] TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 32 | [C030] TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 33 | [CCA9] TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 34 | [CCA8] TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 35 | [C013] TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA 36 | [C014] TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA 37 | [009C] TLS_RSA_WITH_AES_128_GCM_SHA256 38 | [009D] TLS_RSA_WITH_AES_256_GCM_SHA384 39 | [002F] TLS_RSA_AES_128_SHA 40 | [0035] TLS_RSA_AES_256_SHA 41 | [000A] SSL_RSA_WITH_3DES_EDE_SHA 42 | 43 | Compression: 44 | [00] NO_COMPRESSION 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------------------------- 50 | HTTP/1.1 200 Connection Established 51 | FiddlerGateway: Direct 52 | StartTime: 17:12:51.544 53 | Connection: close 54 | 55 | Encrypted HTTPS traffic flows through this CONNECT tunnel. HTTPS Decryption is enabled in Fiddler, so decrypted sessions running in this tunnel will be shown in the Web Sessions list. 56 | 57 | Secure Protocol: Tls12 58 | Cipher: Aes128 128bits 59 | Hash Algorithm: Sha256 ?bits 60 | Key Exchange: ECDHE_RSA (0xae06) 256bits 61 | 62 | == Server Certificate ========== 63 | [Subject] 64 | CN=baidu.com, O="Beijing Baidu Netcom Science Technology Co., Ltd", OU=service operation department, L=beijing, S=beijing, C=CN 65 | 66 | [Issuer] 67 | CN=GlobalSign Organization Validation CA - SHA256 - G2, O=GlobalSign nv-sa, C=BE 68 | 69 | [Serial Number] 70 | 21ED2CC2F1092C666B15E527 71 | 72 | [Not Before] 73 | 2018/4/3 11:26:03 74 | 75 | [Not After] 76 | 2019/5/26 13:31:02 77 | 78 | [Thumbprint] 79 | D6AAF8CFA0E0236547FC2A894F895EC94724A60D 80 | 81 | [SubjectAltNames] 82 | baidu.com, baifubao.com, www.baidu.cn, www.baidu.com.cn, mct.y.nuomi.com, baifae.com, apollo.auto, *.baidu.com, *.baifubao.com, *.baidustatic.com, *.bdstatic.com, *.bdimg.com, *.hao123.com, *.nuomi.com, *.chuanke.com, *.trustgo.com, *.bce.baidu.com, *.eyun.baidu.com, *.map.baidu.com, *.mbd.baidu.com, *.fanyi.baidu.com, *.baidubce.com, *.mipcdn.com, *.news.baidu.com, *.baidupcs.com, *.aipage.com, *.aipage.cn, *.bcehost.com, *.safe.baidu.com, *.im.baidu.com, *.ssl2.duapps.com, *.baifae.com, *.baiducontent.com, *.dlnel.com, *.dlnel.org, *.dueros.baidu.com, *.su.baidu.com, *.91.com, *.hao123.baidu.com, *.apollo.auto, *.xueshu.baidu.com, *.bj.baidubce.com, *.gz.baidubce.com, click.hm.baidu.com, log.hm.baidu.com, cm.pos.baidu.com, wn.pos.baidu.com, update.pan.baidu.com 83 | -------------------------------------------------------------------------------- /https/3..txt: -------------------------------------------------------------------------------- 1 | GET https://www.baidu.com/ HTTP/1.1 2 | Host: www.baidu.com 3 | Connection: keep-alive 4 | Upgrade-Insecure-Requests: 1 5 | User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0 6 | Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 7 | Accept-Encoding: gzip, deflate, sdch, br 8 | Accept-Language: zh-CN,zh;q=0.8 9 | Cookie: sug=3; sugstore=0; ORIGIN=2; bdime=0; PSTM=1548518482; BIDUPSID=AB5D30C3B7D87115386CCC492E40DB33; BAIDUID=FD0398E8AF293C4C21083C95A031CEC0:FG=1; BD_HOME=0; BD_UPN=19314753; H_PS_645EC=2185L%2BkPTpPGO2fWAON6NHytl3vRp6yrM9p3rLGcKmL%2BMlMj8rAiEQw%2BBuI; delPer=0; BD_CK_SAM=1; PSINO=5; H_PS_PSSID=1446_21083_28329_20718; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BDSVRTM=0 10 | 11 | 12 | -------------------------------------------------------------------------------------------------- 13 | HTTP/1.1 200 OK 14 | Bdpagetype: 1 15 | Bdqid: 0xdfccbcfc0001dd79 16 | Cache-Control: private 17 | Connection: Keep-Alive 18 | Content-Encoding: gzip 19 | Content-Type: text/html 20 | Cxy_all: baidu+9153b7f9e52842e4cfc47d66b3266a0b 21 | Date: Sun, 27 Jan 2019 09:12:49 GMT 22 | Expires: Sun, 27 Jan 2019 09:12:49 GMT 23 | Server: BWS/1.1 24 | Set-Cookie: delPer=0; path=/; domain=.baidu.com 25 | Set-Cookie: BDSVRTM=8; path=/ 26 | Set-Cookie: BD_HOME=0; path=/ 27 | Set-Cookie: H_PS_PSSID=1446_21083_28329_20718; path=/; domain=.baidu.com 28 | Strict-Transport-Security: max-age=172800 29 | Vary: Accept-Encoding 30 | X-Ua-Compatible: IE=Edge,chrome=1 31 | Transfer-Encoding: chunked 32 | 33 | d93 34 |    y \ u' 7 P ~Ħ ڷf U Ip( " [U 35 | ]j F / ˒Gc z < ˼[ =a[ 1 | ; d ̛ A Ga Tݛ{ <{ Wn q {o / 36 | 37 | *** FIDDLER: RawDisplay truncated at 128 characters. Right-click to disable truncation. *** -------------------------------------------------------------------------------- /source/ProxyHttpServer.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/e01181235b818299d402b4d9084dd838d654f264/source/ProxyHttpServer.jar -------------------------------------------------------------------------------- /source/cmd-console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/e01181235b818299d402b4d9084dd838d654f264/source/cmd-console.png -------------------------------------------------------------------------------- /source/http-page.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/e01181235b818299d402b4d9084dd838d654f264/source/http-page.png -------------------------------------------------------------------------------- /source/proxy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/e01181235b818299d402b4d9084dd838d654f264/source/proxy.png -------------------------------------------------------------------------------- /source/run.bat: -------------------------------------------------------------------------------- 1 | java -Dfile.encoding=utf-8 -jar ProxyHttpServer.jar -------------------------------------------------------------------------------- /source/run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nICEnnnnnnnLee/ProxyHttpServer/e01181235b818299d402b4d9084dd838d654f264/source/run.png -------------------------------------------------------------------------------- /src/nicelee/config/ConfigReader.java: -------------------------------------------------------------------------------- 1 | package nicelee.config; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.InputStreamReader; 8 | //import java.util.HashMap; 9 | import java.util.regex.Matcher; 10 | import java.util.regex.Pattern; 11 | 12 | import nicelee.config.model.Config; 13 | import nicelee.http.MainApplication; 14 | 15 | public class ConfigReader { 16 | final static Pattern patternConfig = Pattern.compile("^[ ]*([0-9|a-z|A-Z|.|_]+)[ ]*=[ ]*([^ ]+.*$)"); 17 | 18 | /** 19 | * 返回key 所对应的value; 如无设置,返回0 20 | * 21 | * @param property 22 | * @return 23 | */ 24 | public static int getInt(String property) { 25 | try { 26 | return Integer.parseInt(System.getProperty(property)); 27 | } catch (Exception e) { 28 | return 0; 29 | } 30 | } 31 | 32 | /** 33 | * 返回key 所对应的value; 如无设置,返回0 34 | * 35 | * @param property 36 | * @return 37 | */ 38 | public static long getLong(String property) { 39 | try { 40 | return Long.parseLong(System.getProperty(property)); 41 | } catch (Exception e) { 42 | return 0; 43 | } 44 | } 45 | 46 | /** 47 | * 返回key 所对应的value; 如无默认设置,返回null 48 | * 49 | * @param property 50 | * @return 51 | */ 52 | public static String getString(String property) { 53 | return System.getProperty(property); 54 | } 55 | 56 | public static Config initConfigs() { 57 | // 先初始化默认值 58 | BufferedReader buReader = null; 59 | try { 60 | InputStream in = MainApplication.class.getResourceAsStream("/resources/app.config"); 61 | buReader = new BufferedReader(new InputStreamReader(in)); 62 | String config; 63 | while ((config = buReader.readLine()) != null) { 64 | Matcher matcher = patternConfig.matcher(config); 65 | if (matcher.find()) { 66 | System.setProperty(matcher.group(1), matcher.group(2).trim()); 67 | //System.out.printf(" key-->value: %s --> %s\r\n", matcher.group(1), matcher.group(2)); 68 | } 69 | } 70 | buReader.close(); 71 | } catch (IOException e) { 72 | e.printStackTrace(); 73 | } 74 | 75 | //从配置文件读取 76 | buReader = null; 77 | System.out.println("----Config init begin...----"); 78 | try { 79 | buReader = new BufferedReader(new FileReader("app.config")); 80 | String config; 81 | while ((config = buReader.readLine()) != null) { 82 | Matcher matcher = patternConfig.matcher(config); 83 | if (matcher.find()) { 84 | System.setProperty(matcher.group(1), matcher.group(2).trim()); 85 | System.out.printf(" key-->value: %s --> %s\r\n", matcher.group(1), matcher.group(2)); 86 | } 87 | } 88 | } catch (IOException e) { 89 | // e.printStackTrace(); 90 | } finally { 91 | try { 92 | buReader.close(); 93 | } catch (Exception e) { 94 | } 95 | } 96 | System.out.println("----Config ini end...----"); 97 | Config configs = new Config(); 98 | configs.portServerListening = ConfigReader.getInt("nicelee.server.port"); 99 | configs.threadPoolSize = ConfigReader.getInt("nicelee.server.fixedPoolSize"); 100 | configs.sourceLocation = ConfigReader.getString("nicelee.server.source"); 101 | configs.socketTimeout = ConfigReader.getLong("nicelee.server.socketTimeout"); 102 | configs.mode = ConfigReader.getInt("nicelee.server.mode"); 103 | return configs; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/nicelee/config/model/Config.java: -------------------------------------------------------------------------------- 1 | package nicelee.config.model; 2 | 3 | 4 | public class Config { 5 | public static final int MODE_FILE_HTTP_SERVER = 0; 6 | public static final int MODE_PROXY_HTTP_SERVER = 1; 7 | public int mode; 8 | public int portServerListening; 9 | public int threadPoolSize; 10 | public String sourceLocation; 11 | public long socketTimeout; 12 | } 13 | -------------------------------------------------------------------------------- /src/nicelee/http/MainApplication.java: -------------------------------------------------------------------------------- 1 | package nicelee.http; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | 8 | import nicelee.config.ConfigReader; 9 | import nicelee.config.model.Config; 10 | import nicelee.http.core.SocketServer; 11 | 12 | public class MainApplication { 13 | 14 | public static void main(String[] args) throws IOException { 15 | figlet(); 16 | // 1. 从配置文件app.config读取配置 17 | Config configs = ConfigReader.initConfigs(); 18 | 19 | // 2. 启动服务端 20 | SocketServer ss = new SocketServer(configs); 21 | ss.startServer(); 22 | 23 | } 24 | 25 | static void figlet() { 26 | BufferedReader bu = null; 27 | try { 28 | InputStream in = MainApplication.class.getResourceAsStream("/resources/console.display"); 29 | bu = new BufferedReader(new InputStreamReader(in)); 30 | String gg; 31 | while ((gg = bu.readLine()) != null) { 32 | System.out.println(gg); 33 | } 34 | } catch (IOException e) { 35 | e.printStackTrace(); 36 | } finally { 37 | try { 38 | bu.close(); 39 | } catch (Exception e) { 40 | } 41 | } 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/nicelee/http/core/SocketServer.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.core; 2 | 3 | import java.io.IOException; 4 | import java.net.ServerSocket; 5 | import java.net.Socket; 6 | import java.net.SocketException; 7 | import java.net.SocketTimeoutException; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | 11 | import nicelee.config.model.Config; 12 | import nicelee.http.core.runnable.SocketDealer; 13 | import nicelee.http.core.runnable.SocketMonitor; 14 | 15 | public class SocketServer { 16 | 17 | //Configs 18 | int mode; 19 | int portServerListening; 20 | String sourceLocation; 21 | long socketTimeout; 22 | 23 | boolean isRun = true; 24 | public static ExecutorService httpThreadPool; 25 | public static ExecutorService httpProxyThreadPool; 26 | ServerSocket serverSocket; 27 | 28 | public SocketServer(int portServerListening, int threadPoolSize, long socketTimeout, String sourceLocation) { 29 | this.portServerListening = portServerListening; 30 | httpThreadPool = Executors.newFixedThreadPool(threadPoolSize); 31 | httpProxyThreadPool = Executors.newFixedThreadPool(threadPoolSize); 32 | this.sourceLocation = sourceLocation; 33 | this.socketTimeout = socketTimeout; 34 | } 35 | public SocketServer(Config config) { 36 | this.portServerListening = config.portServerListening; 37 | httpThreadPool = Executors.newFixedThreadPool(config.threadPoolSize); 38 | httpProxyThreadPool = Executors.newFixedThreadPool(config.threadPoolSize); 39 | this.sourceLocation = config.sourceLocation; 40 | this.socketTimeout = config.socketTimeout; 41 | this.mode = config.mode; 42 | } 43 | 44 | /** 45 | * 关闭服务器 46 | */ 47 | public void stopServer() { 48 | try { 49 | serverSocket.close(); 50 | } catch (IOException e) { 51 | e.printStackTrace(); 52 | } 53 | System.out.println("正在关闭 SocketServer: 服务器... "); 54 | } 55 | 56 | /** 57 | * 打开服务器 58 | */ 59 | public void startServer() { 60 | Socket socket = null; 61 | System.out.println("SocketServer: 服务器监听开始... "); 62 | try { 63 | serverSocket = new ServerSocket(portServerListening); 64 | //serverSocket.setSoTimeout(300000); 65 | 66 | //开启Socket监控进程, 时间长于socketTimeout的将会被打断 67 | SocketMonitor monitor = new SocketMonitor(socketTimeout); 68 | Thread th = new Thread(monitor); 69 | th.start(); 70 | while (isRun) { 71 | try { 72 | socket = serverSocket.accept(); 73 | }catch (SocketTimeoutException e) { 74 | continue; 75 | }catch (SocketException e) { 76 | break; 77 | } 78 | 79 | //System.out.println("收到新连接: " + socket.getInetAddress() + ":" + socket.getPort()); 80 | SocketDealer dealer = new SocketDealer(socket, monitor, sourceLocation, mode); 81 | httpThreadPool.execute(dealer); 82 | //monitor.put(socket); 改为在线程里面刷新时间(每次Http Request刷新一遍) 83 | } 84 | httpThreadPool.shutdownNow(); 85 | th.interrupt(); 86 | } catch (IOException e) { 87 | e.printStackTrace(); 88 | } finally { 89 | if (socket != null) { 90 | try { 91 | socket.close(); 92 | } catch (IOException e) { 93 | } 94 | } 95 | if (serverSocket != null) { 96 | try { 97 | serverSocket.close(); 98 | } catch (IOException e) { 99 | } 100 | } 101 | } 102 | System.out.println("SocketServer: 服务器已经关闭... "); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/nicelee/http/core/file/transfer/HttpDataTransfer.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.core.file.transfer; 2 | 3 | import java.io.BufferedOutputStream; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.RandomAccessFile; 7 | 8 | public class HttpDataTransfer { 9 | 10 | final static byte[] BREAK_LINE = "\r\n".getBytes(); 11 | 12 | /** 13 | * 缓冲区 14 | */ 15 | byte[] data = new byte[1024 * 8]; 16 | 17 | /** 18 | * 使用断点续传 19 | * 20 | * @param begin 文件起始位置 21 | * @param end 文件结束位置 22 | * @param out 面向客户端的输出流 23 | * @param file 文件 24 | * @throws IOException 25 | */ 26 | public void transferFileWithRange(long begin, long end, BufferedOutputStream out, File file) throws IOException { 27 | 28 | RandomAccessFile raf = new RandomAccessFile(file, "r"); 29 | try { 30 | long cnt = 0, fSize = end - begin + 1; 31 | 32 | out.write("Content-Length: ".getBytes()); 33 | out.write(("" + fSize).getBytes()); 34 | out.write(BREAK_LINE); 35 | 36 | out.write("Content-Range:bytes ".getBytes()); 37 | out.write(("" + begin).getBytes()); 38 | out.write(("-").getBytes()); 39 | out.write(("" + end).getBytes()); 40 | out.write(("/").getBytes()); 41 | out.write(("" + file.length()).getBytes()); 42 | out.write(BREAK_LINE); 43 | 44 | out.write(BREAK_LINE); 45 | raf.seek(begin); 46 | int sizeRead = raf.read(data); 47 | while (sizeRead >= 0) { 48 | if (sizeRead <= fSize - cnt) { 49 | out.write(data, 0, sizeRead); 50 | cnt += sizeRead; 51 | sizeRead = raf.read(data); 52 | } else { 53 | out.write(data, 0, (int) (fSize - cnt)); 54 | break; 55 | } 56 | } 57 | out.flush(); 58 | } catch (IOException e) { 59 | throw e; 60 | } finally { 61 | try { 62 | raf.close(); 63 | } catch (Exception e) { 64 | } 65 | } 66 | 67 | } 68 | 69 | /** 70 | * 使用常见传输方式传输文件 71 | * 72 | * @param out 面向客户端的输出流 73 | * @param file 文件 74 | * @throws IOException 75 | */ 76 | public void transferFileCommon(BufferedOutputStream out, File file) throws IOException { 77 | // System.out.println("Transfering file..."); 78 | RandomAccessFile raf = new RandomAccessFile(file, "r"); 79 | try { 80 | long fSize = file.length(); 81 | // System.out.println("File size: "+ fSize); 82 | out.write("Content-Length: ".getBytes()); 83 | out.write(("" + fSize).getBytes()); 84 | out.write(BREAK_LINE); 85 | out.write(BREAK_LINE); 86 | int sizeRead = raf.read(data); 87 | 88 | while (sizeRead > 0) { 89 | out.write(data, 0, sizeRead); 90 | sizeRead = raf.read(data); 91 | } 92 | out.write(BREAK_LINE); 93 | out.flush(); 94 | } catch (IOException e) { 95 | e.printStackTrace(); 96 | throw e; 97 | } finally { 98 | try { 99 | raf.close(); 100 | } catch (Exception e) { 101 | } 102 | } 103 | } 104 | 105 | /** 106 | * 使用Chunked 方式传输文件 107 | * 108 | * @param out 面向客户端的输出流 109 | * @param file 文件 110 | * @throws IOException 111 | */ 112 | public void transferFileChunked(BufferedOutputStream out, File file) throws IOException { 113 | RandomAccessFile raf = new RandomAccessFile(file, "r"); 114 | try { 115 | System.out.println("准备传输 + "); 116 | out.write("Transfer-Encoding: chunked".getBytes()); 117 | out.write(BREAK_LINE); 118 | out.write(BREAK_LINE); 119 | int sizeRead = raf.read(data); 120 | 121 | while (sizeRead > 0) { 122 | System.out.println("准备传输 + " + String.format("%x", sizeRead)); 123 | out.write(String.format("%x", sizeRead).getBytes()); 124 | out.write(BREAK_LINE); 125 | out.write(data, 0, sizeRead); 126 | out.write(BREAK_LINE); 127 | sizeRead = raf.read(data); 128 | out.flush(); 129 | } 130 | out.write(48); 131 | out.write(BREAK_LINE); 132 | out.write(BREAK_LINE); 133 | out.write(BREAK_LINE); 134 | out.flush(); 135 | } catch (IOException e) { 136 | e.printStackTrace(); 137 | throw e; 138 | } finally { 139 | try { 140 | raf.close(); 141 | } catch (Exception e) { 142 | } 143 | } 144 | 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/nicelee/http/core/file/transfer/HttpHeaderTransfer.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.core.file.transfer; 2 | 3 | import java.io.IOException; 4 | import java.io.BufferedOutputStream; 5 | import java.util.Map.Entry; 6 | 7 | import nicelee.http.model.HttpResponse; 8 | import nicelee.http.resource.HttpResource; 9 | 10 | public class HttpHeaderTransfer { 11 | final static byte[] BREAK_LINE = "\r\n".getBytes(); 12 | 13 | /** 14 | * 设置内容类型 15 | * @param httpResponse 16 | * @param fName 17 | */ 18 | public void setContentType(HttpResponse httpResponse, String fName) { 19 | if(fName.endsWith(".html") || fName.endsWith(".htm") || fName.endsWith(".txt") || fName.endsWith(".md")) { 20 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_HTML+"; charset=UTF-8"; 21 | }else if(fName.endsWith(".js")) { 22 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_JS; 23 | }else if(fName.endsWith(".css")) { 24 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_CSS; 25 | //设置 1 Day 的浏览器缓存时间 26 | long expireTime = System.currentTimeMillis() + HttpResource.DAY_MILLIS; 27 | httpResponse.headers.put("Cache-control", "private"); 28 | httpResponse.headers.put("Expires", HttpResource.GMTDateFormat.format(expireTime)); 29 | }else if(fName.endsWith(".json")) { 30 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_JSON; 31 | }else if(fName.endsWith(".jpg") || fName.endsWith(".png")) { 32 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_JPG; 33 | //设置 1 Day 的浏览器缓存时间 34 | long expireTime = System.currentTimeMillis() + HttpResource.DAY_MILLIS; 35 | httpResponse.headers.put("Cache-control", "private"); 36 | httpResponse.headers.put("Expires", HttpResource.GMTDateFormat.format(expireTime)); 37 | }else if(fName.endsWith(".mp3")) { 38 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_MP3; 39 | }else if(fName.endsWith(".mp4")) { 40 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_MP4; 41 | httpResponse.headers.put("Accept-Ranges", "bytes"); 42 | }else if(fName.endsWith(".ico")) { 43 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_ICO; 44 | //设置 1 Day 的浏览器缓存时间 45 | httpResponse.headers.put("Cache-control", "private"); 46 | long expireTime = System.currentTimeMillis() + HttpResource.DAY_MILLIS; 47 | httpResponse.headers.put("Expires", HttpResource.GMTDateFormat.format(expireTime)); 48 | 49 | }else{ 50 | httpResponse.contentType = HttpResponse.HTTP_CONTENT_TYPE_FILE; 51 | httpResponse.headers.put("Accept-Ranges", "bytes"); 52 | } 53 | } 54 | /** 55 | * 56 | * @param httpResponse 57 | * @param writer 58 | * @throws IOException 59 | */ 60 | public void transferCommonHeader(HttpResponse httpResponse, BufferedOutputStream out) throws IOException { 61 | httpResponse.date = HttpResource.GMTDateFormat.format(System.currentTimeMillis()); 62 | httpResponse.print(); 63 | //System.out.println("doResponse start~"); 64 | 65 | String line = String.format("%s %d %s", httpResponse.version, httpResponse.status, httpResponse.statusDescript); 66 | out.write(line.getBytes()); 67 | out.write(BREAK_LINE); 68 | out.write("Connection:keep-alive".getBytes()); 69 | out.write(BREAK_LINE); 70 | out.write("Date: ".getBytes()); 71 | out.write(httpResponse.date.getBytes()); 72 | out.write(BREAK_LINE); 73 | out.write("Content-Type: ".getBytes()); 74 | out.write(httpResponse.contentType.getBytes()); 75 | out.write(BREAK_LINE); 76 | for(Entry entry : httpResponse.headers.entrySet()) { 77 | out.write((entry.getKey() + ": " + entry.getValue()).getBytes()); 78 | out.write(BREAK_LINE); 79 | } 80 | out.flush(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/nicelee/http/core/file/transfer/common/CommonResponse.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.core.file.transfer.common; 2 | 3 | import java.io.BufferedOutputStream; 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.io.IOException; 7 | import java.io.UnsupportedEncodingException; 8 | import java.util.regex.Matcher; 9 | 10 | import nicelee.http.core.file.transfer.HttpDataTransfer; 11 | import nicelee.http.core.file.transfer.HttpHeaderTransfer; 12 | import nicelee.http.model.HttpRequest; 13 | import nicelee.http.model.HttpResponse; 14 | import nicelee.http.resource.HttpResource; 15 | import nicelee.http.util.StreamReader; 16 | 17 | public class CommonResponse { 18 | 19 | /** 20 | * 根据请求返回 21 | * 22 | * @param httpRequest 23 | * @param reader 24 | * @param writer 25 | */ 26 | public static void doResponseCommon(File srcFolder, HttpRequest httpRequest, StreamReader in, 27 | BufferedOutputStream out) throws IOException { 28 | httpRequest.print(); 29 | HttpResponse httpResponse = new HttpResponse(); 30 | // 盘点是否禁止访问/未授权访问 31 | /** 32 | * 未授权检验 这里以admin:admin为例, 固定生成jsessionid=YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo 33 | * 路径为/source 34 | */ 35 | if (httpRequest.url.startsWith("/source")) { 36 | // System.out.println("访问权限目录..."); 37 | // 如果jsessionid正确, 跳过认证 38 | // boolean sessionCorrect = false; 39 | String cookies = httpRequest.headers.get("cookie"); 40 | if (cookies == null || !HttpResource.patternSessionid.matcher(cookies).find()) { 41 | // System.out.println("未找到匹配session"); 42 | String auth = httpRequest.headers.get("authorization"); 43 | httpRequest.print(); 44 | // 这里用contains不对, 仅作示范用, 表示鉴权通过 45 | if (auth != null && auth.contains("YWRtaW46YWRtaW4")) { 46 | // System.out.println("未找到匹配session,但是鉴权通过"); 47 | httpRequest.headers.put("Set-cookie", 48 | "jsessionid=YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo;path=/;httponly"); 49 | } else { 50 | // System.out.println("未找到匹配session,且鉴权未通过"); 51 | CommonResponse.doResponseWithFileNotAuth(httpResponse, out); 52 | return; 53 | } 54 | // System.out.println("存在匹配session"); 55 | } 56 | } 57 | /** 58 | * 禁止访问检验 路径为*.txt 59 | */ 60 | if (httpRequest.url.endsWith(".txt")) { 61 | CommonResponse.doResponseWithFileForbidden(httpResponse, out); 62 | return; 63 | } 64 | if (isPathExists(srcFolder, httpRequest)) { 65 | // System.out.println("URL Resouce is at: " + httpRequest.url); 66 | File file = new File(srcFolder, httpRequest.url); 67 | if (file.isDirectory()) { 68 | CommonResponse.doResponseWithFolderOK(file, httpRequest, httpResponse, out); 69 | } else { 70 | CommonResponse.doResponseWithFileOK(file, httpRequest, httpResponse, out); 71 | } 72 | } else { 73 | CommonResponse.doResponseWithFileNotFound(httpResponse, out); 74 | } 75 | } 76 | 77 | /** 78 | * 若返回true, 则httpRequest.url已经做了修改,且已经变成了绝对路径 79 | * 80 | * @param httpRequest 81 | * @return 82 | * @throws IOException 83 | */ 84 | public static boolean isPathExists(File srcFolder, HttpRequest httpRequest) throws IOException { 85 | // 去掉锚# 和参数? , 获取path 86 | String path = httpRequest.url; 87 | Matcher matcher = HttpResource.patternURL.matcher(path); 88 | // System.out.println("path路径" +httpRequest.url); 89 | if (matcher.find()) { 90 | path = matcher.group(1); 91 | } else { 92 | System.out.println("path路径不匹配"); 93 | return false; 94 | } 95 | 96 | /** 97 | * 优先顺序, 0文件存在 1不做任何修饰, 文件存在 2文件夹下, index.html/index.htm存在 3path加上.html后缀,文件存在 98 | */ 99 | File file = new File(srcFolder, path); 100 | if (file.exists() && file.isDirectory()) { 101 | return true; 102 | } 103 | if (file.exists()) { 104 | // 匹配 1. 105 | if (file.isFile()) { 106 | return true; 107 | } 108 | } else { 109 | // 匹配 3. 110 | String[] suffixs = { ".html", ".htm" }; 111 | for (String suffix : suffixs) { 112 | File filDst = new File(file.getParent(), file.getName() + suffix); 113 | if (filDst.exists()) { 114 | httpRequest.url += suffix; 115 | return true; 116 | } 117 | } 118 | } 119 | return false; 120 | } 121 | 122 | /** 123 | * 若URL对应的文件不允许访问, 使用该方法返回 124 | * 125 | * @param httpResponse 126 | * @param writer 127 | * @throws IOException 128 | */ 129 | public static void doResponseWithFileForbidden(HttpResponse httpResponse, BufferedOutputStream out) 130 | throws IOException { 131 | HttpHeaderTransfer headerTrans = new HttpHeaderTransfer(); 132 | 133 | // 403 134 | httpResponse.do403(); 135 | httpResponse.dataLength = HttpResource.PAGE_403.length; 136 | headerTrans.transferCommonHeader(httpResponse, out); 137 | 138 | // out date-length & data 139 | out.write("Content-Length: ".getBytes()); 140 | out.write(("" + httpResponse.dataLength).getBytes()); 141 | out.write(HttpResource.BREAK_LINE); 142 | out.write(HttpResource.BREAK_LINE); 143 | out.write(HttpResource.PAGE_403); 144 | out.flush(); 145 | } 146 | 147 | /** 148 | * 若URL对应的文件未经授权认证, 使用该方法返回 149 | * 150 | * @param httpResponse 151 | * @param writer 152 | * @throws IOException 153 | */ 154 | public static void doResponseWithFileNotAuth(HttpResponse httpResponse, BufferedOutputStream out) 155 | throws IOException { 156 | HttpHeaderTransfer headerTrans = new HttpHeaderTransfer(); 157 | 158 | // 401 159 | httpResponse.do401(); 160 | httpResponse.dataLength = HttpResource.PAGE_401.length; 161 | httpResponse.headers.put("WWW-Authenticate", "Basic realm=\"NiceLee's Site\""); 162 | headerTrans.transferCommonHeader(httpResponse, out); 163 | 164 | // out date-length & data 165 | out.write("Content-Length: ".getBytes()); 166 | out.write(("" + httpResponse.dataLength).getBytes()); 167 | out.write(HttpResource.BREAK_LINE); 168 | out.write(HttpResource.BREAK_LINE); 169 | out.write(HttpResource.PAGE_401); 170 | out.flush(); 171 | } 172 | 173 | /** 174 | * 若URL对应的文件不存在, 使用该方法返回 175 | * 176 | * @param httpResponse 177 | * @param writer 178 | * @throws IOException 179 | */ 180 | public static void doResponseWithFileNotFound(HttpResponse httpResponse, BufferedOutputStream out) 181 | throws IOException { 182 | HttpHeaderTransfer headerTrans = new HttpHeaderTransfer(); 183 | 184 | // 404 185 | httpResponse.do404(); 186 | httpResponse.dataLength = HttpResource.PAGE_404.length; 187 | headerTrans.transferCommonHeader(httpResponse, out); 188 | 189 | // out date-length & data 190 | out.write("Content-Length: ".getBytes()); 191 | out.write(("" + httpResponse.dataLength).getBytes()); 192 | out.write(HttpResource.BREAK_LINE); 193 | out.write(HttpResource.BREAK_LINE); 194 | out.write(HttpResource.PAGE_404); 195 | out.flush(); 196 | } 197 | 198 | /** 199 | * 若URL对应的文件不存在, 使用该方法返回 200 | * 201 | * @param httpResponse 202 | * @param writer 203 | * @throws IOException 204 | */ 205 | public static void doResponseWithFileNoChange(HttpResponse httpResponse, BufferedOutputStream out) 206 | throws IOException { 207 | HttpHeaderTransfer headerTrans = new HttpHeaderTransfer(); 208 | 209 | // 304 210 | httpResponse.do304(); 211 | httpResponse.dataLength = 0; 212 | headerTrans.transferCommonHeader(httpResponse, out); 213 | 214 | // out date-length & data 215 | out.write("Content-Length: 0".getBytes()); 216 | out.write(HttpResource.BREAK_LINE); 217 | out.write(HttpResource.BREAK_LINE); 218 | out.flush(); 219 | } 220 | 221 | /** 222 | * 若文件夹解析成功, 按此返回目录 223 | * 224 | * @param fileFolder 225 | * @param httpRequest 226 | * @param httpResponse 227 | * @param out 228 | * @throws IOException 229 | */ 230 | public static void doResponseWithFolderOK(File fileFolder, HttpRequest httpRequest, HttpResponse httpResponse, 231 | BufferedOutputStream out) throws IOException { 232 | if (!httpRequest.url.endsWith("/")) { 233 | httpRequest.url += "/"; 234 | } 235 | // 200 236 | HttpHeaderTransfer headerTrans = new HttpHeaderTransfer(); 237 | httpResponse.do200(); 238 | //httpResponse.headers.put("Last-Modified", HttpResource.GMTDateFormat.format(fileFolder.lastModified())); 239 | // 如果缓存了最新文件, 直接返回304 240 | String cacheTime = httpRequest.headers.get("If-Modified-Since"); 241 | //System.out.println("headers 缓存时间: " + cacheTime); 242 | if (cacheTime != null) { 243 | try { 244 | //System.out.println("对方本地浏览器缓存时间" + HttpResource.GMTDateFormat.parse(cacheTime).getTime() ); 245 | //System.out.println("服务器文件时间" + fileFolder.lastModified() ); 246 | if (HttpResource.GMTDateFormat.parse(cacheTime).getTime() + 1000 >= fileFolder.lastModified()) { 247 | doResponseWithFileNoChange(httpResponse, out); 248 | //System.out.println("对方本地浏览器已有缓存, 返回304"); 249 | return; 250 | } 251 | //System.out.println("对方本地浏览器已有缓存, 但已过时"); 252 | } catch (Exception e) { 253 | e.printStackTrace(); 254 | } 255 | } 256 | 257 | headerTrans.transferCommonHeader(httpResponse, out); 258 | 259 | // out date-length & data 260 | out.write("Transfer-Encoding: chunked".getBytes()); 261 | out.write(HttpResource.BREAK_LINE); 262 | out.write(HttpResource.BREAK_LINE); 263 | out.flush(); 264 | 265 | byte[] head = ("Nicelee.top提供") 266 | .getBytes(); 267 | out.write(String.format("%x", head.length).getBytes()); 268 | out.write(HttpResource.BREAK_LINE); 269 | out.write(head); 270 | out.write(HttpResource.BREAK_LINE); 271 | 272 | // System.out.println("当前url 为: " +httpRequest.url); 273 | byte[] title = String.format("

Index Of %s


", httpRequest.url).getBytes();
274 | 		out.write(String.format("%x", title.length).getBytes());
275 | 		out.write(HttpResource.BREAK_LINE);
276 | 		out.write(title);
277 | 		out.write(HttpResource.BREAK_LINE);
278 | 
279 | 		StringBuilder sb = new StringBuilder();
280 | 		// 列出父级目录
281 | 		Matcher matcher = HttpResource.patternParent.matcher(httpRequest.url);
282 | 		if (matcher.find()) {
283 | 			String parent = matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
284 | 			sb.append("../
"); 285 | 286 | } 287 | // 列出文件夹 288 | for (File childFolder : fileFolder.listFiles()) { 289 | if (childFolder.isDirectory()) { 290 | sb.append("") 291 | .append(childFolder.getName()).append("/
"); 292 | 293 | } 294 | } 295 | // 列出文件 296 | for (File childFile : fileFolder.listFiles()) { 297 | if (childFile.isFile()) { 298 | String fSize = String.valueOf(childFile.length()); 299 | sb.append("") 300 | .append(childFile.getName()).append("") 301 | .append(HttpResource.WHITE_SPACES, 0, 302 | HttpResource.WHITE_SPACES.length - childFile.getName().length()) 303 | .append(HttpResource.aDateFormat.format(childFile.lastModified())) 304 | .append(HttpResource.WHITE_SPACES, 0, HttpResource.WHITE_SPACES.length - fSize.length() - 30) 305 | .append(fSize).append("
"); 306 | } 307 | } 308 | sb.append("

"); 309 | out.write(String.format("%x", sb.length()).getBytes()); 310 | out.write(HttpResource.BREAK_LINE); 311 | out.write(sb.toString().getBytes()); 312 | out.write(HttpResource.BREAK_LINE); 313 | 314 | out.write(48); 315 | out.write(HttpResource.BREAK_LINE); 316 | out.write(HttpResource.BREAK_LINE); 317 | out.write(HttpResource.BREAK_LINE); 318 | out.flush(); 319 | } 320 | 321 | /** 322 | * 若URL对应的文件存在, 使用该方法返回 323 | * 324 | * @param file 325 | * @param httpResponse 326 | * @param writer 327 | * @throws FileNotFoundException 328 | * @throws UnsupportedEncodingException 329 | * @throws IOException 330 | */ 331 | public static void doResponseWithFileOK(File file, HttpRequest httpRequest, HttpResponse httpResponse, 332 | BufferedOutputStream out) throws FileNotFoundException, UnsupportedEncodingException, IOException { 333 | httpResponse.do200(); 334 | httpResponse.dataLength = (int) file.length(); 335 | httpResponse.headers.put("Last-Modified", HttpResource.GMTDateFormat.format(file.lastModified())); 336 | // 如果缓存了最新文件, 直接返回304 337 | String cacheTime = httpRequest.headers.get("If-Modified-Since"); 338 | //System.out.println("headers 缓存时间: " + cacheTime); 339 | if (cacheTime != null) { 340 | try { 341 | //System.out.println("对方本地浏览器缓存时间" + HttpResource.GMTDateFormat.parse(cacheTime).getTime() ); 342 | //System.out.println("服务器文件时间" + file.lastModified() ); 343 | if (HttpResource.GMTDateFormat.parse(cacheTime).getTime() + 1000 >= file.lastModified()) { 344 | doResponseWithFileNoChange(httpResponse, out); 345 | //System.out.println("对方本地浏览器已有缓存, 返回304"); 346 | return; 347 | } 348 | //System.out.println("对方本地浏览器已有缓存, 但已过时"); 349 | } catch (Exception e) { 350 | e.printStackTrace(); 351 | } 352 | } 353 | 354 | HttpHeaderTransfer headerTrans = new HttpHeaderTransfer(); 355 | 356 | String fName = file.getName().toLowerCase(); 357 | headerTrans.setContentType(httpResponse, fName); 358 | 359 | // out date-length & data 360 | HttpDataTransfer dataTrans = new HttpDataTransfer(); 361 | // decide file begin and end if range acquired 362 | String range; 363 | if ((range = httpRequest.headers.get("range")) != null) { 364 | // System.out.println("Range Required: " +range); 365 | Matcher matcher = HttpResource.patternFileRange.matcher(range); 366 | if (matcher.find()) { 367 | long begin = Long.parseLong(matcher.group(1)); 368 | long end = file.length() - 1; 369 | try { 370 | end = Long.parseLong(matcher.group(2)); 371 | end = end < (file.length() - 1) ? end : (file.length() - 1); 372 | } catch (Exception e) { 373 | } 374 | if (begin > 0) { 375 | // System.out.println("206"); 376 | httpResponse.do206(); 377 | } 378 | headerTrans.transferCommonHeader(httpResponse, out); 379 | dataTrans.transferFileWithRange(begin, end, out, file); 380 | } else { 381 | headerTrans.transferCommonHeader(httpResponse, out); 382 | dataTrans.transferFileCommon(out, file); 383 | } 384 | } else { 385 | headerTrans.transferCommonHeader(httpResponse, out); 386 | dataTrans.transferFileCommon(out, file); 387 | } 388 | out.flush(); 389 | } 390 | } 391 | -------------------------------------------------------------------------------- /src/nicelee/http/core/runnable/ProxyDealer.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.core.runnable; 2 | 3 | import java.io.BufferedOutputStream; 4 | import java.io.IOException; 5 | import java.net.Socket; 6 | 7 | import nicelee.http.util.StreamReader; 8 | 9 | /** 10 | * 将服务器的数据转发给客户端 11 | * 12 | * @author LiJia 13 | * 14 | */ 15 | public class ProxyDealer implements Runnable { 16 | Socket socketClient; 17 | Socket socketServer; 18 | // 与客户端之间的联系 19 | StreamReader in; 20 | BufferedOutputStream out; 21 | // 与服务器之间的联系 22 | StreamReader inFromSever; 23 | BufferedOutputStream outToServer; 24 | // Socket监视器 25 | SocketMonitor monitor; 26 | 27 | public ProxyDealer(SocketDealer socketDealer) { 28 | socketClient = socketDealer.getSocketClient(); 29 | socketServer = socketDealer.getSocketServer(); 30 | in = socketDealer.getIn(); 31 | out = socketDealer.getOut(); 32 | inFromSever = socketDealer.getInFromSever(); 33 | outToServer = socketDealer.getOutToServer(); 34 | monitor = socketDealer.getMonitor(); 35 | monitor.put(socketServer); 36 | } 37 | 38 | @Override 39 | public void run() { 40 | try { 41 | 42 | int len = inFromSever.read(inFromSever.readBuffer); 43 | while (len > -1) { 44 | //System.out.println("收到服务器包大小为:"+ len); 45 | //放入监控队列, 等待timeout时间超时后关闭Socket, 此时会抛出异常, 进而结束整个线程 46 | //Socket关闭后, 对应的两个Dealer线程均会抛出异常关闭 47 | monitor.put(socketServer); 48 | //System.out.println("从服务器收到请求: "); 49 | //System.out.println(new String(inFromSever.readBuffer, 0, len)); 50 | out.write(inFromSever.readBuffer, 0, len); 51 | out.flush(); 52 | len = inFromSever.read(inFromSever.readBuffer); 53 | } 54 | } catch (IOException e) { 55 | //e.printStackTrace(); 56 | } finally { 57 | System.out.println(socketServer.getInetAddress() + " Proxy-线程结束..."); 58 | try { 59 | in.close(); 60 | } catch (Exception e) { 61 | } 62 | try { 63 | out.close(); 64 | } catch (Exception e) { 65 | } 66 | try { 67 | socketClient.close(); 68 | } catch (Exception e) { 69 | } 70 | try { 71 | inFromSever.close(); 72 | } catch (Exception e) { 73 | } 74 | try { 75 | outToServer.close(); 76 | } catch (Exception e) { 77 | } 78 | try { 79 | socketServer.close(); 80 | } catch (Exception e) { 81 | } 82 | } 83 | 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/nicelee/http/core/runnable/SocketDealer.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.core.runnable; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.BufferedOutputStream; 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.net.InetSocketAddress; 8 | import java.net.Socket; 9 | import java.net.SocketException; 10 | import java.util.Map.Entry; 11 | import java.util.regex.Matcher; 12 | 13 | import nicelee.config.model.Config; 14 | import nicelee.http.core.SocketServer; 15 | import nicelee.http.core.file.transfer.common.CommonResponse; 16 | import nicelee.http.model.HttpRequest; 17 | import nicelee.http.resource.HttpResource; 18 | import nicelee.http.util.StreamReader; 19 | 20 | public class SocketDealer implements Runnable { 21 | 22 | Socket socketClient; 23 | Socket socketServer; 24 | 25 | // 与客户端之间的联系 26 | StreamReader in; 27 | BufferedOutputStream out; 28 | // 与服务器之间的联系 29 | StreamReader inFromSever; 30 | BufferedOutputStream outToServer; 31 | // Socket监视器 32 | SocketMonitor monitor; 33 | 34 | File srcFolder; 35 | int mode; 36 | int status = HttpResource.HTTP_REQUEST_FIRST; 37 | 38 | public SocketDealer(Socket socketClient, SocketMonitor monitor) { 39 | this.socketClient = socketClient; 40 | this.monitor = monitor; 41 | } 42 | 43 | public SocketDealer(Socket socketClient, SocketMonitor monitor, String source, int mode) { 44 | this.socketClient = socketClient; 45 | this.srcFolder = new File(source); 46 | this.monitor = monitor; 47 | this.mode = mode; 48 | } 49 | 50 | @Override 51 | public void run() { 52 | String url = ""; 53 | try { 54 | // in = new BufferedInputStream(socketClient.getInputStream()); 55 | in = new StreamReader(monitor, socketClient, new BufferedInputStream(socketClient.getInputStream())); 56 | out = new BufferedOutputStream(socketClient.getOutputStream()); 57 | // writer = new BufferedWriter(new 58 | // OutputStreamWriter(socketClient.getOutputStream())); 59 | HttpRequest httpRequest; 60 | while ((httpRequest = in.readHttpRequestStructrue()) != null) { 61 | url = httpRequest.url; 62 | httpRequest.print(); 63 | 64 | if(mode == Config.MODE_FILE_HTTP_SERVER) { 65 | CommonResponse.doResponseCommon(srcFolder, httpRequest, in, out); 66 | 67 | }else { 68 | if (httpRequest.method.toLowerCase().equals("connect")) { 69 | // System.out.println("调用的是connect 方法"); 70 | doProxyConnect(httpRequest); 71 | break; 72 | } else { 73 | // System.out.println("调用的是普通GET/POST 方法"); 74 | doProxyNormal(httpRequest); 75 | } 76 | } 77 | } 78 | 79 | if(mode == Config.MODE_PROXY_HTTP_SERVER) { 80 | 81 | // 直接转发TCP包, 不做任何处理 82 | // System.out.println("当前开始转发TCP包: "); 83 | while (true) { 84 | int length = in.read(in.readBuffer); 85 | // System.out.println("当前收到客户端包大小: " + length); 86 | outToServer.write(in.readBuffer, 0, length); 87 | outToServer.flush(); 88 | } 89 | } 90 | 91 | } catch (SocketException e) { 92 | // e.printStackTrace(); 93 | } catch (IOException e) { 94 | // e.printStackTrace(); 95 | } catch (IndexOutOfBoundsException e) { 96 | } catch (Exception e) { 97 | e.printStackTrace(); 98 | } finally { 99 | System.out.println(url + " -线程结束..."); 100 | try { 101 | in.close(); 102 | } catch (Exception e) { 103 | } 104 | try { 105 | out.close(); 106 | } catch (Exception e) { 107 | } 108 | try { 109 | socketClient.close(); 110 | } catch (Exception e) { 111 | } 112 | try { 113 | inFromSever.close(); 114 | } catch (Exception e) { 115 | } 116 | try { 117 | outToServer.close(); 118 | } catch (Exception e) { 119 | } 120 | try { 121 | socketServer.close(); 122 | } catch (Exception e) { 123 | } 124 | } 125 | } 126 | 127 | /** 128 | * @param httpRequest 129 | * @throws IOException 130 | */ 131 | private void doProxyConnect(HttpRequest httpRequest) throws IOException { 132 | // System.out.println("调用的是connect 方法"); 133 | connecToServer(httpRequest); 134 | out.write("HTTP/1.1 200 Connection Established\r\n\r\n".getBytes()); 135 | out.flush(); 136 | } 137 | 138 | /** 139 | * @param httpRequest 140 | * @throws IOException 141 | */ 142 | private void doProxyNormal(HttpRequest httpRequest) throws IOException { 143 | // TODO do something with the httpRequest. Put 'X-forward...', for example. 144 | httpRequest.headers.put("X-Forwarded-For", "123.123.123.123"); 145 | // TODO do URLFilter 146 | 147 | // TODO give the client a response, proxy or http 148 | // CommonResponse.doResponseCommon(srcFolder, httpRequest, in, out); 149 | 150 | connecToServer(httpRequest); 151 | // 向服务器发送Http请求 152 | // System.out.println("发送Http请求... "); 153 | outToServer.write( 154 | String.format("%s %s %s\r\n", httpRequest.method, httpRequest.url, httpRequest.version).getBytes()); 155 | outToServer.flush(); 156 | outToServer.write(String.format("Host: %s\r\n", httpRequest.host).getBytes()); 157 | for (Entry entry : httpRequest.headers.entrySet()) { 158 | // TODO do some filter or change 159 | if (!entry.getKey().toLowerCase().contains("proxy") && !entry.getKey().toLowerCase().contains("forward") 160 | && !entry.getKey().toLowerCase().contains("authorization")) { 161 | outToServer.write((entry.getKey() + ": " + entry.getValue()).getBytes()); 162 | outToServer.write(HttpResource.BREAK_LINE); 163 | } 164 | } 165 | httpRequest.print(); 166 | if (httpRequest.dataLength > 0) { 167 | 168 | outToServer.write(String.format("Content-Length: %d\r\n", httpRequest.dataLength).getBytes()); 169 | } 170 | outToServer.write(HttpResource.BREAK_LINE); 171 | outToServer.flush(); 172 | if (httpRequest.dataLength > 0) { 173 | int count = 0; 174 | int rSize = in.read(in.readBuffer); 175 | System.out.println(new String(in.readBuffer, 0, rSize)); 176 | while (rSize < httpRequest.dataLength - count) { 177 | outToServer.write(in.readBuffer, 0, rSize); 178 | rSize = in.read(in.readBuffer); 179 | count += rSize; 180 | } 181 | outToServer.write(in.readBuffer, 0, httpRequest.dataLength - count); 182 | } 183 | outToServer.flush(); 184 | // System.out.println("数据发送完毕..."); 185 | } 186 | 187 | /** 188 | * @param httpRequest 189 | * @throws IOException 190 | */ 191 | private void connecToServer(HttpRequest httpRequest) throws IOException { 192 | String dstIp = httpRequest.host; 193 | int dstPort = 80; 194 | // connect方法, 从首行url获取参数 195 | if (httpRequest.method.toLowerCase().equals("connect")) { 196 | dstPort = 443; 197 | dstIp = httpRequest.url; 198 | } 199 | // 获取目的Host 200 | Matcher matcher = HttpResource.patternHost.matcher(dstIp); 201 | if (matcher.find()) { 202 | dstIp = matcher.group(1); 203 | dstPort = Integer.parseInt(matcher.group(2)); 204 | } 205 | System.out.print("Host为:"); 206 | System.out.print(dstIp); 207 | System.out.print(" ;ip为:"); 208 | System.out.println(dstPort); 209 | if (socketServer == null) { 210 | socketServer = new Socket(); 211 | socketServer.connect(new InetSocketAddress(dstIp, dstPort)); 212 | // socketServer.connect(new InetSocketAddress("127.0.0.1", 7778)); 213 | 214 | // 获取服务器之间的输入输出流 215 | inFromSever = new StreamReader(monitor, socketServer, 216 | new BufferedInputStream(socketServer.getInputStream())); 217 | outToServer = new BufferedOutputStream(socketServer.getOutputStream()); 218 | 219 | // 打开面向服务器的监听线程,专用于转发数据给客户端 220 | ProxyDealer proxyDealer = new ProxyDealer(this); 221 | SocketServer.httpProxyThreadPool.execute(proxyDealer); 222 | } 223 | } 224 | 225 | public Socket getSocketClient() { 226 | return socketClient; 227 | } 228 | 229 | public Socket getSocketServer() { 230 | return socketServer; 231 | } 232 | 233 | public StreamReader getIn() { 234 | return in; 235 | } 236 | 237 | public BufferedOutputStream getOut() { 238 | return out; 239 | } 240 | 241 | public StreamReader getInFromSever() { 242 | return inFromSever; 243 | } 244 | 245 | public BufferedOutputStream getOutToServer() { 246 | return outToServer; 247 | } 248 | 249 | public SocketMonitor getMonitor() { 250 | return monitor; 251 | } 252 | 253 | } 254 | -------------------------------------------------------------------------------- /src/nicelee/http/core/runnable/SocketMonitor.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.core.runnable; 2 | 3 | import java.io.IOException; 4 | import java.net.Socket; 5 | import java.util.Map.Entry; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | public class SocketMonitor implements Runnable{ 9 | 10 | static ConcurrentHashMap socketMap = new ConcurrentHashMap<>(); 11 | 12 | long socketTimeout = 60000; 13 | 14 | public SocketMonitor(long socketTimeout) { 15 | this.socketTimeout = socketTimeout; 16 | } 17 | 18 | public void put(Socket socket) { 19 | //System.out.println("socketMap放入/更新了一个socket..."); 20 | socketMap.put(socket, System.currentTimeMillis()); 21 | } 22 | 23 | public void remove(Socket socket) { 24 | //System.out.println("socketMap取消了一个socket的队列监控..."); 25 | socketMap.remove(socket); 26 | } 27 | 28 | @Override 29 | public void run() { 30 | System.out.println(); 31 | while(true) { 32 | for(Entry entry: socketMap.entrySet()) { 33 | //System.out.println("监控进程判断中..."); 34 | if(entry.getKey().isClosed()) { 35 | socketMap.remove(entry.getKey()); 36 | }else if( System.currentTimeMillis() - entry.getValue() >= socketTimeout ) { 37 | try { 38 | entry.getKey().close(); 39 | //System.out.println("关闭Socket成功..."); 40 | } catch (IOException e) { 41 | //System.out.println("关闭Socket失败..."); 42 | e.printStackTrace(); 43 | } 44 | socketMap.remove(entry.getKey()); 45 | } 46 | } 47 | try { 48 | //System.out.println("监控进程运行中..."); 49 | Thread.sleep(30000); 50 | } catch (InterruptedException e) { 51 | break; 52 | } 53 | } 54 | 55 | 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/nicelee/http/model/HttpRequest.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.model; 2 | 3 | import java.util.HashMap; 4 | 5 | public class HttpRequest { 6 | 7 | /** 8 | * GET/POST/PUT/DELETE ... 9 | */ 10 | public String method; 11 | /** 12 | * HTTP/1.1 13 | */ 14 | public String version; 15 | /** 16 | * e.g. nicele.top:8080 17 | */ 18 | public String host; 19 | /** 20 | * e.g. hello?say=nihao 21 | */ 22 | public String url; 23 | public HashMap headers = new HashMap<>(); 24 | 25 | public int dataLength = 0; 26 | public byte[] data = null; 27 | 28 | public void print() { 29 | // System.out.println(method + " "+ url + " " + version); 30 | // for(Entry entry : headers.entrySet()) { 31 | // System.out.println("------>" +entry.getKey() + ": " + entry.getValue()); 32 | // } 33 | // if(data != null) 34 | // System.out.println(data); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/nicelee/http/model/HttpResponse.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.model; 2 | 3 | import java.util.HashMap; 4 | 5 | public class HttpResponse { 6 | public final static String HTTP_VERSION_1_1 = "HTTP/1.1"; 7 | public final static int HTTP_STATUS_200 = 200; 8 | public final static int HTTP_STATUS_206 = 206; 9 | public final static int HTTP_STATUS_304 = 304; 10 | public final static int HTTP_STATUS_404 = 404; 11 | public final static int HTTP_STATUS_403 = 403; 12 | public final static int HTTP_STATUS_401 = 401; 13 | public final static String HTTP_STATUS_Desc_200_OK = "OK"; 14 | public final static String HTTP_STATUS_Desc_206_Part = "Partial Content"; 15 | public final static String HTTP_STATUS_Desc_304_NOT_MODIFIED = "Not Modified"; 16 | public final static String HTTP_STATUS_Desc_401_NOT_AUTH = "Authorization Required"; 17 | public final static String HTTP_STATUS_Desc_404_NOT_FOUND = "Not Found"; 18 | public final static String HTTP_STATUS_Desc_403_FORBBIDEN = "Forbidden"; 19 | public final static String HTTP_CONTENT_TYPE_HTML = "text/html"; 20 | public final static String HTTP_CONTENT_TYPE_JS = "application/x-javascript"; 21 | public final static String HTTP_CONTENT_TYPE_JSON = "application/json"; 22 | public final static String HTTP_CONTENT_TYPE_CSS = "text/css"; 23 | public final static String HTTP_CONTENT_TYPE_JPG = "image/jpeg"; 24 | public final static String HTTP_CONTENT_TYPE_ICO = "image/x-icon"; 25 | public final static String HTTP_CONTENT_TYPE_FONT = "application/x-font-woff"; 26 | public final static String HTTP_CONTENT_TYPE_MP4 = "video/mp4"; 27 | public final static String HTTP_CONTENT_TYPE_MP3 = "audio/mp3"; 28 | public final static String HTTP_CONTENT_TYPE_FLV = "video/x-flv"; 29 | public final static String HTTP_CONTENT_TYPE_FILE = "application/octet-stream"; 30 | 31 | /** 32 | * HTTP/1.1 33 | */ 34 | public String version = HTTP_VERSION_1_1; 35 | /** 36 | * e.g. 200, 404 37 | */ 38 | public int status = HTTP_STATUS_200; 39 | /** 40 | * e.g. OK, Not Found, Forbidden 41 | */ 42 | public String statusDescript = HTTP_STATUS_Desc_200_OK; 43 | /** 44 | * GMT String 45 | */ 46 | public String date; 47 | /** 48 | * text/html, application/x-javascript, application/json, image/webp, application/x-font-woff, video/mp4 49 | */ 50 | public String contentType = HTTP_CONTENT_TYPE_HTML;//; charset=utf-8 51 | public HashMap headers = new HashMap(); 52 | 53 | public int dataLength = 0; 54 | 55 | public HttpResponse do200() { 56 | return this; 57 | } 58 | 59 | public HttpResponse do206() { 60 | status = HTTP_STATUS_206; 61 | statusDescript = HTTP_STATUS_Desc_206_Part; 62 | return this; 63 | } 64 | public HttpResponse do304() { 65 | status = HTTP_STATUS_304; 66 | statusDescript = HTTP_STATUS_Desc_304_NOT_MODIFIED; 67 | return this; 68 | } 69 | public HttpResponse do404() { 70 | status = HTTP_STATUS_404; 71 | statusDescript = HTTP_STATUS_Desc_404_NOT_FOUND; 72 | return this; 73 | } 74 | 75 | public HttpResponse do403() { 76 | status = HTTP_STATUS_403; 77 | statusDescript = HTTP_STATUS_Desc_403_FORBBIDEN; 78 | return this; 79 | } 80 | 81 | public HttpResponse do401() { 82 | status = HTTP_STATUS_401; 83 | statusDescript = HTTP_STATUS_Desc_401_NOT_AUTH; 84 | return this; 85 | } 86 | 87 | public void print() { 88 | 89 | // System.out.println("返回Response结果: "); 90 | // System.out.println(version + " "+ status + " " + statusDescript); 91 | // System.out.println("Date: "+ date); 92 | // System.out.println("Content-Type: "+ contentType); 93 | // System.out.println("Content-Length: "+ dataLength); 94 | // for(Entry entry : headers.entrySet()) { 95 | // System.out.println(entry.getKey() + ": " + entry.getValue()); 96 | // } 97 | // if(data != null) 98 | // System.out.println(data); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/nicelee/http/resource/HttpResource.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.resource; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Locale; 5 | import java.util.regex.Pattern; 6 | 7 | public class HttpResource { 8 | public final static long HOUR_MILLIS = 60*60*1000; 9 | public final static int DAY_MILLIS = 24*60*60*1000; 10 | public final static int HTTP_REQUEST_FIRST = 0; 11 | public final static int HTTP_REQUEST_AFTER_GET = 0x01; 12 | public final static int HTTP_REQUEST_AFTER_CONNECT = 0x02; 13 | public final static Pattern patternHeaders = Pattern.compile("^([^:]+):(.*)$"); 14 | public final static Pattern patternHost = Pattern.compile("^ *([0-9|a-z|A-Z|.]+) *: *([0-9]*) *$"); 15 | public final static Pattern patternFileRange = Pattern.compile("^bytes=([0-9]+)-([0-9]*)$"); 16 | public final static Pattern patternURL = Pattern.compile("^/([^?^#]*)#?[^#]*\\??[^?^#]*$"); 17 | public final static Pattern patternParent = Pattern.compile("^(/.*)/[^/]+/$|^(/)[^/]+/$"); 18 | public final static Pattern patternSessionid = Pattern 19 | .compile("jsessionid *[=|:]{1} *YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo"); 20 | public final static SimpleDateFormat aDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 21 | // Thu, 31 Jan 2019 08:01:48 GMT || Thu Jan 2410:23:01 GMT 2019 22 | public final static SimpleDateFormat GMTDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'",Locale.US); 23 | public final static byte[] BREAK_LINE = "\r\n".getBytes(); 24 | public final static byte[] PAGE_401 = "Error

401 Authorization Required


Copyright @Nicelee.top
" 25 | .getBytes(); 26 | public final static byte[] PAGE_403 = "Error

403 Forbidden


Copyright @Nicelee.top
" 27 | .getBytes(); 28 | public final static byte[] PAGE_404 = "Error

404 Not Found


Copyright @Nicelee.top
" 29 | .getBytes(); 30 | public final static char[] WHITE_SPACES = " ".toCharArray(); 31 | } 32 | -------------------------------------------------------------------------------- /src/nicelee/http/util/StreamReader.java: -------------------------------------------------------------------------------- 1 | package nicelee.http.util; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.IOException; 5 | import java.net.Socket; 6 | import java.net.SocketException; 7 | import java.nio.ByteBuffer; 8 | import java.util.regex.Matcher; 9 | 10 | import nicelee.http.core.runnable.SocketMonitor; 11 | import nicelee.http.model.HttpRequest; 12 | import nicelee.http.resource.HttpResource; 13 | 14 | 15 | /** 16 | * 用于从输入字节流中提取换行符前的内容 17 | * @author LiJia 18 | * 19 | */ 20 | public class StreamReader { 21 | public byte[] readBuffer; //用于Socket数据读取 22 | ByteBuffer byteBuffer = null; //用于数据缓冲 23 | int maxSize = 2048; 24 | 25 | BufferedInputStream in; 26 | 27 | //用于Socket监控 28 | SocketMonitor monitor; 29 | Socket socketClient; 30 | 31 | public StreamReader(SocketMonitor monitor, Socket socketClient, BufferedInputStream in) { 32 | this.monitor = monitor; 33 | this.socketClient = socketClient; 34 | this.in = in; 35 | readBuffer = new byte[1024]; 36 | byteBuffer = ByteBuffer.allocate(2560); 37 | } 38 | 39 | public void close() throws IOException{ 40 | in.close(); 41 | } 42 | /** 43 | * 从输入流中截取换行符\r\n, 读取前面的内容,并以String返回 44 | * maxSize后仍旧未读出换行符,抛出异常, 45 | * 多余的内容在byteBuffer 46 | * @param byteBuffer 47 | * @return 48 | * throws IOException 49 | */ 50 | public String readLine() throws IOException{ 51 | int cnt = 0, rSize; 52 | //System.out.println("调用readLine方法"); 53 | while(true) { 54 | //从byteBuffer中检查内容 55 | int position = byteBuffer.position(); 56 | for(int i = 0 ; i< position; i++) { 57 | if( byteBuffer.get(i) == 13 && byteBuffer.get(i+1) == 10) { 58 | //构造String 59 | String line = new String(byteBuffer.array(), 0, i ); 60 | if(i + 2 <= position) { 61 | //将ByteBuffer多余的内容去掉 62 | byteBuffer.position(0); 63 | byteBuffer.put(byteBuffer.array(), i + 2, position - i - 2); 64 | }else { 65 | byteBuffer.clear(); 66 | } 67 | //返回结果 68 | //System.out.println(Thread.currentThread().getName()+" -byteBuffer剩余数据(从上一次留存的byteBuffer中找到CRLF)" + (byteBuffer.position())); 69 | //System.out.println(Thread.currentThread().getName()+" 剩余结果" + new String(byteBuffer.array(), 0, byteBuffer.position() )); 70 | return line; 71 | } 72 | } 73 | if(byteBuffer.get(position) == 13) { 74 | int nextByte = in.read(); 75 | if(nextByte == 10) { 76 | String line = new String(byteBuffer.array(), 0, position); 77 | byteBuffer.clear(); 78 | //System.out.println(Thread.currentThread().getName()+" -byteBuffer剩余数据(从上一次留存的byteBuffer中找到CR没找到LF)" + (byteBuffer.position())); 79 | return line; 80 | }else { 81 | byteBuffer.put((byte)nextByte); 82 | } 83 | } 84 | 85 | //从流中读取内容 86 | rSize = in.read(readBuffer); 87 | if(rSize == -1) { 88 | throw new IOException("对方停止传输前, 仍旧未找到回车换行符! "); 89 | } 90 | for(int i = 0 ; i< rSize - 1; i++) { 91 | //找到\r\n 92 | if(readBuffer[i] == 13 && readBuffer[i+1] == 10) { 93 | //构造String 94 | byteBuffer.put(readBuffer, 0, i); 95 | String line = new String(byteBuffer.array(), 0, byteBuffer.position()); 96 | 97 | //将从流中读取多余的内容移至ByteBuffer 98 | byteBuffer.clear(); 99 | if( i+ 2 <= rSize - 1) { 100 | byteBuffer.put(readBuffer, i+ 2, rSize - 2 - i); 101 | } 102 | //返回结果 103 | //System.out.println(Thread.currentThread().getName()+" -byteBuffer剩余数据(从socket中找到CRLF)" + (byteBuffer.position() + 1)); 104 | return line; 105 | } 106 | } 107 | //未找到换行符 108 | //字符长度过大,返回null 109 | cnt += rSize; 110 | if(cnt > maxSize) { 111 | //System.out.println("长度过大, 仍旧未找到回车换行符: " + maxSize); 112 | throw new IOException("长度过大, 仍旧未找到回车换行符! "); 113 | } 114 | //System.out.println("大小" +rSize); 115 | //将内容移至ByteBuffer 116 | byteBuffer.put(readBuffer, 0, rSize); 117 | } 118 | } 119 | 120 | 121 | /** 122 | * 返回HttpRequest结构, 不符合协议标准将会抛出异常 123 | * 124 | * @param reader return 125 | * @throws IOException 126 | */ 127 | public HttpRequest readHttpRequestStructrue() 128 | throws NullPointerException, IOException, IndexOutOfBoundsException { 129 | // refresh the monitor 130 | monitor.put(socketClient); 131 | // System.out.println("Headers 提取中... 可能会阻塞或抛出异常..."); 132 | HttpRequest httpRequest = new HttpRequest(); 133 | 134 | // 第一行 135 | String firstLine = readLine(); 136 | if (firstLine == null) { 137 | return null; 138 | } 139 | //System.out.println("第一行为: " + firstLine); 140 | String firstLines[] = firstLine.split(" "); 141 | httpRequest.method = firstLines[0]; 142 | httpRequest.url = firstLines[1]; 143 | httpRequest.version = firstLines[2]; 144 | // 第一行结束 145 | 146 | // 获取其他属性 147 | String key_value = readLine(); 148 | while (key_value != null && key_value.length() > 0) { 149 | //System.out.println(key_value); 150 | // System.out.println("获取数据中..."); 151 | Matcher matcher = HttpResource.patternHeaders.matcher(key_value); 152 | matcher.find(); 153 | String key = matcher.group(1).trim(); 154 | String value = matcher.group(2).trim(); 155 | if (key.toLowerCase().startsWith("host")) { 156 | // 获取目的host 157 | httpRequest.host = value; 158 | }else if (key.toLowerCase().startsWith("content-length")) { 159 | // 判断是否有数据 160 | httpRequest.dataLength = Integer.parseInt(value); 161 | }else { 162 | httpRequest.headers.put(key, value); 163 | } 164 | key_value = readLine(); 165 | //System.out.println(Thread.currentThread().getName()+"当前key_value..." + key_value); 166 | //System.out.println(Thread.currentThread().getName()+"当前key_value长度:" + key_value.getBytes().length); 167 | } 168 | //System.out.println(Thread.currentThread().getName()+"最后bytebuffer剩余数据..." + byteBuffer.position()); 169 | // System.out.println("获取httpRequest完毕..."); 170 | 171 | // 内容传输不计入时间, 则从监控队列删除 172 | // monitor.remove(socketClient); 173 | return httpRequest; 174 | } 175 | 176 | public int read(byte[] b, int off, int len) throws IOException, SocketException { 177 | 178 | if (byteBuffer.position() == 0) { 179 | //System.out.println("byteBuffer为空"); 180 | return in.read(b, off, len); 181 | } 182 | int pos = byteBuffer.position(); 183 | if (len > pos) { 184 | //System.out.println("部分从byteBuffer中读取"); 185 | System.arraycopy(byteBuffer.array(), 0, b, off, pos); 186 | int rSize = in.read(b, off + pos, len - pos); 187 | //System.out.println("部分从流中读取"); 188 | byteBuffer.clear(); 189 | return rSize + pos; 190 | } else { 191 | //System.out.println("全部从byteBuffer中读取"); 192 | System.arraycopy(byteBuffer.array(), 0, b, off, len); 193 | byteBuffer.position(0); 194 | byteBuffer.put(byteBuffer.array(), len, pos - len); 195 | return len; 196 | } 197 | } 198 | 199 | public int read(byte[] b) throws IOException { 200 | if(b == readBuffer && byteBuffer.position() > 0) { 201 | return read(b, 0, byteBuffer.position()); 202 | } 203 | return read(b, 0, b.length); 204 | } 205 | 206 | /** 207 | * 效率低,不推荐使用 208 | * @return 209 | * @throws IOException 210 | */ 211 | public int read() throws IOException { 212 | if (byteBuffer.position()==0) { 213 | return in.read(); 214 | } 215 | int b = byteBuffer.get(0); 216 | int pos = byteBuffer.position(); 217 | byteBuffer.position(0); 218 | byteBuffer.put(byteBuffer.array(), 1, pos -1); 219 | return b; 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /src/resources/console.display: -------------------------------------------------------------------------------- 1 | _ _ _ 2 | (_) | | | | 3 | _ __ _ ___ ___| | ___ ___ | |_ ___ _ __ 4 | | '_ \| |/ __/ _ \ |/ _ \/ _ \| __/ _ \| '_ \ 5 | | | | | | (_| __/ | __/ __/| || (_) | |_) | 6 | |_| |_|_|\___\___|_|\___|\___(_)__\___/| .__/ 7 | | | 8 | |_| --------------------------------------------------------------------------------