在这些示例中,您可以找到创建简单代理套接字服务器的不同方法。由于多种原因,这对您很有用:

  • 捕获客户端和服务器之间的流量。
  • 限制上传/下载带宽,以了解您的网站是如何加载慢速连接的。
  • 查看网络出现问题时系统的反应。
  • "动态"修改客户端/服务器的内容(发送的接收)。
  • 生成有关流量的统计信息。

*您可以使用此处的示例作为开发的基础。尚未实现任何功能。以下示例只是代理。您不能总是将它们用作 HTTP 代理。

示例 1(多插槽代理服务器)

使用示例 1 作为另一个 HTTP 代理的 HTTP 代理

示例 2(同时只有 1 个插槽)

示例 3 HTTP 代理

示例 1

import java.io.*;
import java.net.*;/**** @author jcgonzalez.com**/
public class ProxyMultiThread {public static void main(String[] args) {try {if (args.length != 3)throw new IllegalArgumentException("insuficient arguments");// and the local port that we listen for connections onString host = args[0];int remoteport = Integer.parseInt(args[1]);int localport = Integer.parseInt(args[2]);// Print a start-up messageSystem.out.println("Starting proxy for " + host + ":" + remoteport + " on port " + localport);ServerSocket server = new ServerSocket(localport);while (true) {new ThreadProxy(server.accept(), host, remoteport);}} catch (Exception e) {System.err.println(e);System.err.println("Usage: java ProxyMultiThread " + "<host> <remoteport> <localport>");}}
}/*** Handles a socket connection to the proxy server from the client and uses 2* threads to proxy between server and client** @author jcgonzalez.com**/
class ThreadProxy extends Thread {private Socket sClient;private final String SERVER_URL;private final int SERVER_PORT;ThreadProxy(Socket sClient, String ServerUrl, int ServerPort) {this.SERVER_URL = ServerUrl;this.SERVER_PORT = ServerPort;this.sClient = sClient;this.start();}@Overridepublic void run() {try {final byte[] request = new byte[1024];byte[] reply = new byte[4096];final InputStream inFromClient = sClient.getInputStream();final OutputStream outToClient = sClient.getOutputStream();Socket client = null, server = null;// connects a socket to the servertry {server = new Socket(SERVER_URL, SERVER_PORT);} catch (IOException e) {PrintWriter out = new PrintWriter(new OutputStreamWriter(outToClient));out.flush();throw new RuntimeException(e);}// a new thread to manage streams from server to client (DOWNLOAD)final InputStream inFromServer = server.getInputStream();final OutputStream outToServer = server.getOutputStream();// a new thread for uploading to the servernew Thread() {public void run() {int bytes_read;try {while ((bytes_read = inFromClient.read(request)) != -1) {outToServer.write(request, 0, bytes_read);outToServer.flush();// TODO CREATE YOUR LOGIC HERE}} catch (IOException e) {}try {outToServer.close();} catch (IOException e) {e.printStackTrace();}}}.start();// current thread manages streams from server to client (DOWNLOAD)int bytes_read;try {while ((bytes_read = inFromServer.read(reply)) != -1) {outToClient.write(reply, 0, bytes_read);outToClient.flush();// TODO CREATE YOUR LOGIC HERE}} catch (IOException e) {e.printStackTrace();} finally {try {if (server != null)server.close();if (client != null)client.close();} catch (IOException e) {e.printStackTrace();}}outToClient.close();sClient.close();} catch (IOException e) {e.printStackTrace();}}
}

编译和使用

javac ProxyMultiThread.java

java ProxyMultiThread 192.168.1.10 8080 9999

在端口 9999 上启动 192.168.1.10:8180 的代理

(现在流量通过代理从localhost 9999重定向到192.168.1.10。请记住,由于HTTP主机标签,引用程序,javascript重定向等原因,Web浏览器可能并不总是有效。

使用示例 1 作为另一个 HTTP 代理的 HTTP 代理

如果您的 HTTP 代理在端口380myproxy.test.net,并且您希望在 java 到达代理之前使用 java 作为代理,则应按如下方式运行它。

java ProxyMultiThread myproxy.test.net 80 9999

现在调整浏览器配置以使用本地主机 9999 上的代理

在火狐浏览器中:

*现在,您的所有流量都应该先转到示例1,然后再转到您的代理。

示例 2


// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.io.*;
import java.net.*;/*** This class implements a simple single-threaded proxy server.**/
public class SimpleProxyServer {/** The main method parses arguments and passes them to runServer */public static void main(String[] args) throws IOException {try {// Check the number of argumentsif (args.length != 3)throw new IllegalArgumentException("Wrong number of arguments.");// Get the command-line arguments: the host and port we are proxy for// and the local port that we listen for connections onString host = args[0];int remoteport = Integer.parseInt(args[1]);int localport = Integer.parseInt(args[2]);// Print a start-up messageSystem.out.println("Starting proxy for " + host + ":" + remoteport + " on port " + localport);// And start running the serverrunServer(host, remoteport, localport); // never returns} catch (Exception e) {System.err.println(e);System.err.println("Usage: java SimpleProxyServer " + "<host> <remoteport> <localport>");}}/*** This method runs a single-threaded proxy server for host:remoteport on the* specified local port. It never returns.**/public static void runServer(String host, int remoteport, int localport) throws IOException {// Create a ServerSocket to listen for connections withServerSocket ss = new ServerSocket(localport);// Create buffers for client-to-server and server-to-client communication.// We make one final so it can be used in an anonymous class below.// Note the assumptions about the volume of traffic in each direction...final byte[] request = new byte[1024];byte[] reply = new byte[4096];// This is a server that never returns, so enter an infinite loop.while (true) {// Variables to hold the sockets to the client and to the server.Socket client = null, server = null;try {// Wait for a connection on the local portclient = ss.accept();// Get client streams. Make them final so they can// be used in the anonymous thread below.final InputStream from_client = client.getInputStream();final OutputStream to_client = client.getOutputStream();// Make a connection to the real server// If we cannot connect to the server, send an error to the// client, disconnect, then continue waiting for another connection.try {server = new Socket(host, remoteport);} catch (IOException e) {PrintWriter out = new PrintWriter(new OutputStreamWriter(to_client));out.println("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e);out.flush();client.close();continue;}// Get server streams.final InputStream from_server = server.getInputStream();final OutputStream to_server = server.getOutputStream();// Make a thread to read the client's requests and pass them to the// server. We have to use a separate thread because requests and// responses may be asynchronous.new Thread() {public void run() {int bytes_read;try {while ((bytes_read = from_client.read(request)) != -1) {to_server.write(request, 0, bytes_read);System.out.println(bytes_read + "to_server--->" + new String(request, "UTF-8") + "<---");to_server.flush();}} catch (IOException e) {}// the client closed the connection to us, so close our// connection to the server. This will also cause the// server-to-client loop in the main thread exit.try {to_server.close();} catch (IOException e) {}}}.start();// Meanwhile, in the main thread, read the server's responses// and pass them back to the client. This will be done in// parallel with the client-to-server request thread above.int bytes_read;try {while ((bytes_read = from_server.read(reply)) != -1) {try {Thread.sleep(1);System.out.println(bytes_read + "to_client--->" + new String(request, "UTF-8") + "<---");} catch (InterruptedException e) {e.printStackTrace();}to_client.write(reply, 0, bytes_read);to_client.flush();}} catch (IOException e) {}// The server closed its connection to us, so close our// connection to our client. This will make the other thread exit.to_client.close();} catch (IOException e) {System.err.println(e);}// Close the sockets no matter what happens each time through the loop.finally {try {if (server != null)server.close();if (client != null)client.close();} catch (IOException e) {}}} // while(true)}
}

示例 3 HTTP 代理

我使用Benjamin Kohl&Artem Melnik的HTTP Java Proxy下载这里或转到原始网站这里.

笔记

  • 您可以使用Thread.sleep来限制带宽,抛出随机异常以扰乱网络,修改内容等。

Java 创建带有套接字的简单代理服务器示例相关推荐

  1. Java网络编程套接字

    文章目录 1.网络编程基础 2.什么是网络编程 3.网络编程中的基本概念 3.1.发送端和接收端 3.2 请求和响应 3.3 客户端和服务端 3.4 常见的客户端服务端模型 4.Socket套接字 4 ...

  2. java套接字客户端_使用Java从客户端套接字读取数据(Read data from a client socket in Java)...

    使用Java从客户端套接字读取数据(Read data from a client socket in Java) 我编写了从客户端套接字发送/接收数据的代码. 发送数据步骤已成功完成,但是当我想从套 ...

  3. java原始套接字,raw socket介绍(示例代码)

    原文: http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=876233 test 1.原始套接字(raw socket) 1.1 原始 ...

  4. Win10创建原始套接字失败原因及解决方法

    2019/04/21 转载自https://blog.csdn.net/qq_26399665/article/details/52859146 //创建原始套接字 m_s=socket(AF_INE ...

  5. Java NIO之套接字通道

    1.简介 前面一篇文章讲了文件通道,本文继续来说说另一种类型的通道 – 套接字通道.在展开说明之前,咱们先来聊聊套接字的由来.套接字即 socket,最早由伯克利大学的研究人员开发,所以经常被称为Be ...

  6. 关于Java中数据报套接字DatagramSocket中connet()方法说明

    大家都知道UDP协议是面向无连接的,但是用于UDP的DatagramSocket类中却有connet()方法,实在令人费解.刚才有学生问起来,研究了下才发现这个方法的真正用法! connet()方法共 ...

  7. (积累)java里的套接字

    上计算机网络实验课,有个作业是关于java套接字编程的,总结一下吧! 1. 建立一个服务端套接字: ServerSocket s = new ServerSocket(12343);     // 默 ...

  8. java 函数式编程 示例_Java套接字编程–套接字服务器,客户端示例

    java 函数式编程 示例 Welcome to Java Socket programming example. Every server is a program that runs on a s ...

  9. java使用原始套接字技术进行数据包截获_Linux零拷贝技术,看完这篇文章就懂了...

    本文讲解 Linux 的零拷贝技术,云计算是一门很庞大的技术学科,融合了很多技术,Linux 算是比较基础的技术,所以,学好 Linux 对于云计算的学习会有比较大的帮助. 为什么需要零拷贝 传统的 ...

最新文章

  1. 用于Fluent Design的UWP社区工具包蓄势待发
  2. OpenCV4 DNN模块 Python APIs
  3. OpenCV 开闭运算
  4. [css] 请用css写一个扫码的加载动画图
  5. Python----常用模块1
  6. 找找看XSS漏洞!!!
  7. html5透明图片格式,半透明图片制作
  8. x64 - reject driver loading
  9. 计算机word中的宏,word运行宏快捷键_WORD运行宏_word中运行宏的方法_word自动运行宏...
  10. 简单易懂的ROC曲线和AUC面积
  11. java取模数_java – 快速乘法和减法模数
  12. MFC实现基本图形绘制、变换、自由曲线绘制、图形裁剪和填充
  13. python矩阵操作:dot、inv、det、eig
  14. vue滚动屏幕使其菜单栏隐藏和显示
  15. MySQL insert 插入优化技巧,MySQL 优化学习第8天
  16. 混合策略纳什均衡——附例题及解析
  17. 普元连接mysql_普元数据库面试题
  18. 数据矿工学习-样本自适应的在线卷积稀疏编码论文-个人中文翻译
  19. 分享几个互联网求职神器,搞明白了,春招再严峻也不用担心!
  20. 小米平板4(Plus) LTE 开通话模式教程+root权限获取

热门文章

  1. 大脑构造图与功能解析_大脑结构与功能
  2. NXP JN5169 读写片外 FLASH
  3. python基于pingouin包进行统计分析:使用pairwise_tukey函数执行Tukey检验进行事后分析(Pairwise Tukey post-hocs)
  4. Redis框架(三):大众点评项目 基于Session的短信登录
  5. sort和sortby的区别:
  6. 【可爱甜美圆嘟嘟的孩子壁纸】
  7. 会员权益营销中,设置会员权益的三个标准
  8. /bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)
  9. WPS的Excel做一个下拉选择功能
  10. Google秘密入口