Skip to content

Commit

Permalink
格式化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
ztgreat committed Nov 16, 2019
1 parent 1341e7c commit e7edc6c
Show file tree
Hide file tree
Showing 57 changed files with 1,014 additions and 933 deletions.
34 changes: 17 additions & 17 deletions proxy-client/src/main/java/com/proxy/client/ProxyClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ public class ProxyClient {
/**
* 服务器端口,默认6666
*/
private int port;
private int port;

/**
* 5M
*/
private int maxContentLength = 5*1024 * 1024;
private int maxContentLength = 5 * 1024 * 1024;


/**
Expand All @@ -65,9 +65,9 @@ public class ProxyClient {
private NioEventLoopGroup realServerGroup;


public ProxyClient(){
this.host="127.0.0.1";
this.port=6666;
public ProxyClient() {
this.host = "127.0.0.1";
this.port = 6666;
clientBootstrap = new Bootstrap();
clientGroup = new NioEventLoopGroup();
}
Expand Down Expand Up @@ -95,8 +95,8 @@ public void start() throws InterruptedException {
public void initChannel(SocketChannel ch)
throws Exception {
//ch.pipeline().addLast("logs", new LoggingHandler(LogLevel.DEBUG));
ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(10*3, 15*3, 20*3));
ch.pipeline().addLast(new ProxyMessageDecoder(2*1024*1024,0,4));
ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(10 * 3, 15 * 3, 20 * 3));
ch.pipeline().addLast(new ProxyMessageDecoder(2 * 1024 * 1024, 0, 4));
ch.pipeline().addLast(new ProxyMessageEncoder());
ch.pipeline().addLast(new LoginAuthReqHandler());
ch.pipeline().addLast(new HeartBeatReqHandler());
Expand All @@ -114,7 +114,7 @@ public void initChannel(SocketChannel ch)

try {
clear();
}catch (Exception e){
} catch (Exception e) {

}

Expand All @@ -123,7 +123,7 @@ public void initChannel(SocketChannel ch)
/**
* 初始化 连接后端真正服务器
*/
public void initRealServerBoot(){
public void initRealServerBoot() {

//初始化
realServerBootstrap = new Bootstrap();
Expand All @@ -145,14 +145,14 @@ public void initChannel(SocketChannel ch) throws Exception {

public void doConnect(int retry) throws InterruptedException {

if (retry ==0)
if (retry == 0)
return;
ChannelFuture future = clientBootstrap.connect(host, port);
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture futureListener) throws Exception {
if (futureListener.isSuccess()) {
Channel channel = futureListener.channel();
logger.info("连接服务器({})成功",host);
logger.info("连接服务器({})成功", host);

channel.closeFuture().addListeners(new ChannelFutureListener() {
@Override
Expand All @@ -164,16 +164,16 @@ public void operationComplete(ChannelFuture channelFuture) throws Exception {
});

} else {
logger.info("连接服务器({}) 失败,10s后尝试重连",host);
logger.info("连接服务器({}) 失败,10s后尝试重连", host);
}
}
});
future.channel().closeFuture().sync();
Thread.sleep(10000);
doConnect(retry-1);
doConnect(retry - 1);
}

public void clear(){
public void clear() {
ClientBeanManager.getProxyService().clear();
clientGroup.shutdownGracefully();
realServerGroup.shutdownGracefully();
Expand All @@ -183,9 +183,9 @@ public static void main(String[] args) throws Exception {

//加载日志
LogBackConfigLoader.load();
String host= ClientBeanManager.getConfigService().readConfig().get("server.host");
String port= ClientBeanManager.getConfigService().readConfig().get("server.port");
new ProxyClient(host,Integer.valueOf(port)).start();
String host = ClientBeanManager.getConfigService().readConfig().get("server.host");
String port = ClientBeanManager.getConfigService().readConfig().get("server.port");
new ProxyClient(host, Integer.valueOf(port)).start();
}

}
3 changes: 3 additions & 0 deletions proxy-client/src/main/java/com/proxy/client/cache/Cache.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,23 @@ public interface Cache<K, V> {

/**
* 获取缓存数据
*
* @param key
* @return
*/
V get(K key);

/**
* 保存缓存数据
*
* @param key
* @param v
*/
void put(K key, V v);

/**
* 移除某个缓存数据
*
* @param key
*/
void remove(K key);
Expand Down
17 changes: 9 additions & 8 deletions proxy-client/src/main/java/com/proxy/client/dao/ConfigDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,25 @@

public class ConfigDao {

private static Map<String,String >config;
public Map<String,String> readConfig() throws Exception{
if (config!=null){
private static Map<String, String> config;

public Map<String, String> readConfig() throws Exception {
if (config != null) {
return config;
}
InputStream in=this.getClass().getClassLoader().getResourceAsStream("client.properties");
if(in ==null){
InputStream in = this.getClass().getClassLoader().getResourceAsStream("client.properties");
if (in == null) {
String filePath = "../conf/client.properties";
in = new BufferedInputStream(new FileInputStream(filePath));
}
Properties prop = new Properties();
prop.load(in);

Set keys = prop.keySet();
config= new HashMap<>();
for (Iterator<String> it = keys.iterator(); it.hasNext();){
config = new HashMap<>();
for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
String key = it.next();
config.put(key,prop.getProperty(key));
config.put(key, prop.getProperty(key));
}
return config;
}
Expand Down
24 changes: 13 additions & 11 deletions proxy-client/src/main/java/com/proxy/client/dao/ProxyDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,49 +10,51 @@

public class ProxyDao {

private static CacheManager<Long,RealServer> cacheManager =new MemoryCacheManager<Long,Channel>();
private static CacheManager<Long, RealServer> cacheManager = new MemoryCacheManager<Long, Channel>();

private static Cache<Long,RealServer> realServerChannels = cacheManager.getCache("proxy_cache");
private static Cache<Long, RealServer> realServerChannels = cacheManager.getCache("proxy_cache");

/**
* 代理客户端和代理服务器的通道
*/
private volatile Channel channel;
private volatile Channel channel;

public void setChannel(Channel channel) {
public void setChannel(Channel channel) {
this.channel = channel;
}

public Channel getChannel() {
public Channel getChannel() {
return channel;
}

public Long getRealServerChannelSessionID(Channel realServerChannel) {
public Long getRealServerChannelSessionID(Channel realServerChannel) {
return Long.valueOf(realServerChannel.attr(CommonConstant.SESSION_ID).get());
}

public RealServer getRealServerChannel(Long sessionID) {
public RealServer getRealServerChannel(Long sessionID) {
return realServerChannels.get(sessionID);
}

public void addRealServerChannel(Long sessionID, RealServer realServer, Channel realServerChannel,String proxyType,String proxyServer) {
public void addRealServerChannel(Long sessionID, RealServer realServer, Channel realServerChannel, String proxyType, String proxyServer) {
realServerChannels.put(sessionID, realServer);
realServerChannel.attr(CommonConstant.SESSION_ID).set(String.valueOf(sessionID));
realServerChannel.attr(CommonConstant.UserChannelAttributeKey.TYPE).set(proxyType);
realServerChannel.attr(CommonConstant.UserChannelAttributeKey.PROXYSERVER).set(proxyServer);
}
public void removeRealServerChannel(Long sessionID){

public void removeRealServerChannel(Long sessionID) {
realServerChannels.remove(sessionID);
}

public void clear(){
public void clear() {
realServerChannels.clear();
this.channel=null;
this.channel = null;
}

public int getProxyType(Channel realServerChannel) {
return Integer.valueOf(realServerChannel.attr(CommonConstant.UserChannelAttributeKey.TYPE).get());
}

public String getProxyServer(Channel realServerChannel) {
return realServerChannel.attr(CommonConstant.UserChannelAttributeKey.PROXYSERVER).get();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public ClientHandler(Bootstrap realServerBootStrap) {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

ProxyMessage message= (ProxyMessage) msg;
ProxyMessage message = (ProxyMessage) msg;
byte type = message.getType();
switch (type) {
case CommonConstant.MessageType.TYPE_TRANSFER:
Expand All @@ -47,64 +47,66 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
break;
}
}

private void handleTransferMessage(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
Long sessionID = proxyMessage.getSessionID();

RealServer realServer= ClientBeanManager.getProxyService().getRealServerChannel(sessionID);
RealServer realServer = ClientBeanManager.getProxyService().getRealServerChannel(sessionID);
Channel realServerChannel = null;
if ((realServer !=null) && (realServerChannel=realServer.getChannel()) != null) {
if ((realServer != null) && (realServerChannel = realServer.getChannel()) != null) {

byte requestType=proxyMessage.getProxyType();
if (requestType== CommonConstant.ProxyType.TCP){
byte requestType = proxyMessage.getProxyType();
if (requestType == CommonConstant.ProxyType.TCP) {

//1.如果消息是tcp类型
ByteBuf buf = ctx.alloc().buffer(proxyMessage.getData().length);
buf.writeBytes(proxyMessage.getData());
realServerChannel.writeAndFlush(buf);
logger.debug("客户端转发tcp请求至真实服务器");

}else if(requestType== CommonConstant.ProxyType.HTTP) {
} else if (requestType == CommonConstant.ProxyType.HTTP) {

//2.如果消息是http类型
ByteBuf buf = ctx.alloc().buffer(proxyMessage.getData().length);
buf.writeBytes(proxyMessage.getData());
ctx.fireChannelRead(buf);
}

}else {
} else {
logger.debug("代理客户端未连接真实服务器,需要重新发起连接请求");

// TODO: 2018/2/22 需要fix

//方案1:通知服务器关闭用户的请求,让用户重新发起新的连接
//目前:检测到和真实服务器失去连接后,会通知代理服务器断开与用户的连接
proxyMessage = ProxyMessageUtil.buildReConnect(sessionID,null);
proxyMessage = ProxyMessageUtil.buildReConnect(sessionID, null);
ctx.channel().writeAndFlush(proxyMessage);

//方案2:缓存数据,客户端重新与真实服务器建立连接,当连接建立成功后,再转发数据

}
}

private void handleConnectMessage(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {

final Channel channel = ctx.channel();

//会话id
final Long sessionID = proxyMessage.getSessionID();
//代理类型
int proxyType=proxyMessage.getProxyType() & 0xFF;
int proxyType = proxyMessage.getProxyType() & 0xFF;

//代理服务器地址,用于重定向的时候替换header 中的Location地址
final String proxyServer=new String(proxyMessage.getCommand());
final String proxyServer = new String(proxyMessage.getCommand());

//真实服务器地址:ip:port
String[] serverInfo = new String(proxyMessage.getData()).split(":");

//真实服务器ip
final String ip = serverInfo[0];
final String ip = serverInfo[0];

//真实服务器端口
final int port = Integer.parseInt(serverInfo[1]);
final int port = Integer.parseInt(serverInfo[1]);


realServerBootStrap.connect(ip, port).addListener(new ChannelFutureListener() {
Expand All @@ -115,7 +117,7 @@ public void operationComplete(ChannelFuture future) throws Exception {

Channel realServerChannel = future.channel();

logger.debug("客户端连接真实服务器成功{}",ip+":"+port);
logger.debug("客户端连接真实服务器成功{}", ip + ":" + port);

RealServer realServer = new RealServer();

Expand All @@ -125,14 +127,14 @@ public void operationComplete(ChannelFuture future) throws Exception {
realServer.setProxyType(proxyType);
realServer.setStatus(CommonConstant.ProxyStatus.ONLINE);

ClientBeanManager.getProxyService().addRealServerChannel(sessionID,realServer,realServerChannel,String.valueOf(proxyType),proxyServer);
ClientBeanManager.getProxyService().addRealServerChannel(sessionID, realServer, realServerChannel, String.valueOf(proxyType), proxyServer);


ProxyMessage proxyMessage = ProxyMessageUtil.buildConnectSuccess(sessionID,null);
ProxyMessage proxyMessage = ProxyMessageUtil.buildConnectSuccess(sessionID, null);
channel.writeAndFlush(proxyMessage);
} else {
logger.error("客户端连接真实服务器({})失败:{}",ip+":"+port+" "+future.cause().getMessage());
ProxyMessage proxyMessage = ProxyMessageUtil.buildConnectFail(sessionID,null);
logger.error("客户端连接真实服务器({})失败:{}", ip + ":" + port + " " + future.cause().getMessage());
ProxyMessage proxyMessage = ProxyMessageUtil.buildConnectFail(sessionID, null);
channel.writeAndFlush(proxyMessage);
}
}
Expand All @@ -144,15 +146,15 @@ private void handleDisConnectMessage(ChannelHandlerContext ctx, ProxyMessage pro
Long sessionID = proxyMessage.getSessionID();

String[] serverInfo = new String(proxyMessage.getData()).split(":");
final String ip = serverInfo[0];
final int port = Integer.parseInt(serverInfo[1]);
final String ip = serverInfo[0];
final int port = Integer.parseInt(serverInfo[1]);

RealServer realServer =ClientBeanManager.getProxyService().getRealServerChannel(sessionID);
Channel realServerChannel=null ;
if (realServer !=null && (realServerChannel=realServer.getChannel()) != null) {
RealServer realServer = ClientBeanManager.getProxyService().getRealServerChannel(sessionID);
Channel realServerChannel = null;
if (realServer != null && (realServerChannel = realServer.getChannel()) != null) {
realServerChannel.close();
ClientBeanManager.getProxyService().removeRealServerChannel(sessionID);
logger.debug("客户端与真实服务器{}断开",ip+":"+port);
logger.debug("客户端与真实服务器{}断开", ip + ":" + port);
}

}
Expand All @@ -169,7 +171,7 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E

ClientBeanManager.getProxyService().clear();
ctx.channel().close();
logger.error("发生异常:清理数据,客户端退出"+cause.getMessage());
logger.error("发生异常:清理数据,客户端退出" + cause.getMessage());
}

@Override
Expand Down
Loading

0 comments on commit e7edc6c

Please sign in to comment.