socketProxy

7 篇文章 0 订阅

一个Socket代理,主要用来监听socket通信。


package org.sl.socket;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * 代理处理器
 * @author shanl
 *
 */
class ProxyHandler implements Runnable{
	private Socket socket = null;
	private SocketAddress address = null;
	
	private Socket client = null;
	private OutputStream readFileOut = null;
	private OutputStream writeFileOut = null;	
	private long time = 0;	
	private boolean close = true;
	
	/**
	 * 构造器
	 * @param client 客户端Socket
	 * @param toAddress 要连接到的地址
	 * @throws IOException
	 */
	public ProxyHandler(Socket client, SocketAddress toAddress) throws IOException{
		this.socket = client;
		this.address = toAddress;
		
		init();
	}
	
	public void setSocketReadOutputStream(OutputStream readFileOut){
		this.readFileOut = readFileOut;
	}
	
	public void setSocketWriteOutputStream(OutputStream writeFileOut){
		this.writeFileOut = writeFileOut;
	}
	
	private void init() throws IOException{
		this.close = false;
		//创建一个向指定地址连接的Socket
		this.client = new Socket();
		this.client.connect(address);
		
		this.time = System.currentTimeMillis()/3&0xffff;
	}
	
	private void initOutputStream()throws IOException{
		if(null == this.readFileOut){
			this.readFileOut = new FileOutputStream("d:\\test\\listen\\read_"+time+".dt");
		}
		
		if(null == this.writeFileOut){
			this.writeFileOut = new FileOutputStream("d:\\test\\listen\\writer_"+time+".dt");
		}
	}
	
	/**
	 * 启动服务
	 */
	public void start(){
		this.close = false;
		new Thread(this).start();
	}
	
	public void run(){	
		InputStream clientIn = null;
		OutputStream clientOut = null;
		
		InputStream socketIn = null;
		OutputStream socketOut = null;
		
		SocketWriter read = null;
		SocketWriter writer = null;		
		
		try{
			System.out.println("proxy(id:"+time+") start...");
			
			if(client.isConnected()){
				initOutputStream();
				
				clientIn = client.getInputStream();
				clientOut = client.getOutputStream();
				
				socketIn = this.socket.getInputStream();
				socketOut = this.socket.getOutputStream();
				
				read = new SocketWriter(this, clientIn, socketOut, "read_"+time);
				writer = new SocketWriter(this, socketIn, clientOut, "writer_"+time);
				
				read.enabledPrint(readFileOut);
				writer.enabledPrint(writeFileOut);
				
				read.start();
				writer.start();
			}
		}catch(Exception ex){
			ex.printStackTrace();
			close();
		}
	}
		
	/**
	 * 关闭相关资源
	 */
	synchronized public void close(){
		if(close){
			return;
		}
		
		System.out.println("关闭连接(address:"+address+")资源.");
		close = true;
		
		try{
			if(null != client){
				client.close();
				client = null;
			}
		}catch(Exception ex0){				
		}
		
		try{
			if(null != socket){
				socket.close();
				socket = null;
			}
		}catch(Exception ex0){				
		}
		
		try{
			if(null != readFileOut){
				readFileOut.close();
				readFileOut = null;
			}
		}catch(Exception ex0){				
		}
		
		try{
			if(null != writeFileOut){
				writeFileOut.close();
				writeFileOut = null;
			}
		}catch(Exception ex0){				
		}
	}
}





package org.sl.socket;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * 代理服务器端
 * @author shanl
 *
 */
public class ProxyServer {
	private SocketAddress address = null;
	private int listenPort = 7771;
	
	/**
	 * 构造器
	 * @param address 要连接到的地址
	 */
	public ProxyServer(SocketAddress address){
		this.address = address;
	}
	
	/**
	 * 构造器
	 * @param ip 要连接到的IP
	 * @param port 要连接到的端口
	 */
	public ProxyServer(String ip, int port){
		address = new InetSocketAddress(ip, port);
	}
	
	/**
	 * 设置监听端口,默认端口7771,<b>必需在start()前被执行</b>
	 * @param port
	 */
	public void setListenPort(int port){
		this.listenPort = port;
	}
	
	/**
	 * 启动服务
	 */
	public void start(){
		ServerSocket server = null;
		Socket client = null;
		ProxyHandler proxy = null;
		
		try{
			System.out.println("proxy server start(port:"+listenPort+")...");
			server = new ServerSocket(listenPort);
			
			for(int i = 0; ;i++){				
				client = server.accept();
				System.out.println("connect client "+i);

				proxy = new ProxyHandler(client, address);
				proxy.start();
			}
		}catch(Exception ex){
			ex.printStackTrace();
			
			try {
				server.close();
			} catch (Exception e) {
			}
		}
	}	
	
}


package org.sl.socket;

//import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//import java.net.Socket;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 负责在两个socket之间数据传输
 * @author Shanl
 *
 */
class SocketWriter implements Runnable{
	private ProxyHandler handler = null;
	private InputStream in = null;
	private OutputStream out = null;
	
	private OutputStream dataOut = null;
	
	private boolean print = false;
	private SimpleDateFormat dateFormat = new SimpleDateFormat("[HH:mm:ss.S] ");
	private static final byte[] newLine = new byte[]{'\r', '\n'};
	private String name = null;
	
	/**
	 * 构造器
	 * @param handler 代理处理器
	 * @param in 输入流
	 * @param out 输出流
	 * @param name 助记及调试名
	 */
	public SocketWriter(ProxyHandler handler, InputStream in, OutputStream out, String name){
		this.handler = handler;
		this.in = in;
		this.out = out;
		this.name = name;
	}
	
	public void run(){
		int buffer_size = 5000;
		byte[] buffer = new byte[buffer_size];
		int readLen = 0;
		
		try{			
			while(-1 != (readLen = in.read(buffer, 0, buffer_size))){
				out.write(buffer, 0, readLen);
				
				//打印字节数据
				if(print){
					print(buffer, readLen);
				}
			}
		}catch(SocketException ex){
			handler.close();
		}catch(Exception ex){
			ex.printStackTrace();
			handler.close();
		}		
	}
	
	/**
	 * 启动
	 */
	public void start(){
		new Thread(this, name).start();
	}
	
	/**
	 * 设置并激活数据记录输出流,<b>必需要start()前被调用.</b>
	 * @param out
	 */
	public void enabledPrint(OutputStream out){
		this.print = true;
		this.dataOut = out;
	}
	
	private void print(byte[] buffer, int len){
		print(dataOut, buffer, len);
	}
	
	private void print(OutputStream out, byte[] buffer, int len){
		try {
			out.write(dateFormat.format(new Date()).getBytes());
			out.write(buffer, 0, len);
			out.write(newLine);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}


测试类

import org.sl.socket.ProxyServer;


public class ListenServerTest1 {
	public static void main(String[] args){
		t1();
	}
	
	static void t1(){
		ProxyServer server = new ProxyServer("192.168.0.81", 21);
		server.setListenPort(7777);
		server.start();
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中可以使用socket模块来实现简单的代理服务器。以下是一个简单的示例: ```python import socket def proxy_server(ip, port, target_ip, target_port): # 创建一个socket对象 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定ip和端口号 server_socket.bind((ip, port)) # 监听连接 server_socket.listen(1) print('Proxy server is listening on port ' + str(port) + '...') while True: # 等待客户端连接 client_socket, addr = server_socket.accept() print('Connected to ' + str(addr)) # 连接目标服务器 target_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) target_socket.connect((target_ip, target_port)) print('Connected to target server ' + target_ip + ':' + str(target_port)) # 接收客户端发送的数据并发送给目标服务器 while True: data = client_socket.recv(1024) if not data: break target_socket.send(data) # 接收目标服务器发送的数据并发送给客户端 while True: data = target_socket.recv(1024) if not data: break client_socket.send(data) # 关闭连接 target_socket.close() client_socket.close() print('Connection closed') ``` 在这个示例中,我们创建了一个名为proxy_server()的函数,它接受四个参数:代理服务器的IP地址、代理服务器的端口号、目标服务器的IP地址和目标服务器的端口号。代理服务器会监听指定的端口,并等待客户端连接。一旦有客户端连接,代理服务器会连接目标服务器,并将客户端发送的数据转发给目标服务器,同时将目标服务器发送的数据转发给客户端。 请注意,这个示例只是一个非常简单的代理服务器示例,它没有进行任何错误处理或安全性检查。在实际应用中,请务必进行适当的错误处理和安全性检查。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值