-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPProxyServer.java
77 lines (64 loc) · 2.91 KB
/
TCPProxyServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import threadPool.ProxyThreadPool;
import lruCache.LRUcache;
import requestHandler.TcpHandler;
import requestHandler.httpHandler.HttpHandler;
import java.net.*;
import java.io.*;
import java.util.Scanner;
import client.javaClient.client;
import configurations.Config;
public class TCPProxyServer {
public static void main(String args[]) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
int serverPort = Config.serverPort;
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(serverPort);
System.out.println("Proxy Server is listening on port: " + serverPort);
// spinning up a thread pool
ProxyThreadPool threadPool = new ProxyThreadPool(Config.corePoolSize, Config.maxPoolSize, Config.keepAliveTime);
// setup cache
LRUcache cache = new LRUcache(Config.cacheSize);
switch (Config.serverType) {
case TCP:
while (true) {
Socket clientSocket = serverSocket.accept();
String clientIP = clientSocket.getInetAddress().toString();
int clientPort = clientSocket.getPort();
System.out.println("Client connected on " + clientIP + ":" + clientPort);
System.out.println("Client connected on " + clientIP + ":" + clientPort);
if(Config.blacklistedIPs.contains(clientIP)){
System.out.println("Blacklisted IP");
clientSocket.close();
continue;
}
if (cache.get(clientIP) != null) {
String data = cache.get(clientIP);
OutputStream outToClient = clientSocket.getOutputStream();
outToClient.write(data.getBytes());
continue;
}
// connecting to a destination server
threadPool.submitTask(new TcpHandler(Config.tcpServerHost,
Config.tcpServerPort, clientSocket, cache));
sc.close();
}
case HTTP:
while (true) {
Socket clientSocket = serverSocket.accept();
String clientIP = clientSocket.getInetAddress().toString();
int clientPort = clientSocket.getPort();
System.out.println("Client connected on " + clientIP + ":" + clientPort);
if(Config.blacklistedIPs.contains(clientIP)){
System.out.println("Blacklisted IP");
clientSocket.close();
continue;
}
threadPool.submitTask(new HttpHandler(clientSocket));
sc.close();
}
default:
break;
}
sc.close();
}
}