Skip to content

Commit

Permalink
Project files added...
Browse files Browse the repository at this point in the history
  • Loading branch information
enesgarip committed Feb 8, 2021
1 parent 060029c commit a5cec2b
Show file tree
Hide file tree
Showing 65 changed files with 3,083 additions and 1 deletion.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
96 changes: 96 additions & 0 deletions 2020 Computer Networks/Project/ProxyServer/ProxyServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Java Proxy Server Implementation
// Abdullah Gülçür - 150116014
// Enes Garip - 150116034

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ProxyServer {
public static void main(String[] args) {
int localPort = 8888; // port number of the proxy
System.out.println("Proxy server is started.\nPort:" + localPort);
try {
ServerSocket server = new ServerSocket(localPort); //creating a server socket
while (true){
Socket socket= server.accept();
new ThreadProxy(socket);
}
} catch (IOException e) {
System.out.println("Server socket Error!!");
}
}
}
class ThreadProxy extends Thread{
String finalRequest; // holds the the last version of the request
Socket sClient; // socket for client
String response; // holds the response
ThreadProxy(Socket sClient){
this.sClient=sClient;
this.start();
}
@Override
public void run(){ // Thread starts..
final byte[] request = new byte[1024]; // holds request from the client
try {
// i/o Streams for the client..
InputStream inFromClient = sClient.getInputStream();
PrintWriter outToClientWriter=new PrintWriter(sClient.getOutputStream());
new Thread() { // new thread
public void run() {
try {
while ((inFromClient.read(request)) != -1) {
String s=new String(request, StandardCharsets.UTF_8); // reads the request byte by byte
if(s.split("\n")[0].split(" ")[0].equals("GET")){
System.out.println("\n-----Request From Client to Proxy Server-----");
System.out.println(s.split("\n")[0]); // request of the client..
System.out.println("-----End of Request-----\n");
if(s.split("\n")[0].length()>20) {
String requestFromClient = s.split(" ")[1];
String portNumber = requestFromClient.split(":")[2].split("/")[0];
Socket server = new Socket("localhost", Integer.parseInt(portNumber));
final InputStream inFromServer = server.getInputStream();// i/o Streams for the server..
final OutputStream outToServer = server.getOutputStream();// i/o Streams for the server..
String sizeCheck = requestFromClient.split("/")[3];
if (sizeCheck.matches("\\d+")) {
int sizeNumber = Integer.parseInt(sizeCheck);
finalRequest="GET /"+sizeNumber+" HTTP/1.1";
if (sizeNumber > 9999) { // size restriction...
System.out.println("414 Request-URI Too Long");
}else if (sizeNumber<100){ // size restriction..
System.out.println("Bad Request!!");
}
else {
BufferedReader bf = new BufferedReader(new InputStreamReader(inFromServer));//buffer for server to proxy communication
outToServer.write(finalRequest.getBytes(StandardCharsets.UTF_8)); // writing the final request to the server
outToServer.write("\n".getBytes(StandardCharsets.UTF_8));
outToServer.flush();
System.out.println("-----Response to the Client-----");
while (((response = bf.readLine()) != null)) { //forwarding web server's response to the client
System.out.println(response); //console output
outToClientWriter.println(response);// browser output
outToClientWriter.flush();
}
System.out.println("-----Response to the Client-----Ended.");
}
// closing the sockets
outToServer.close();
sClient.close();
server.close();
} else System.out.println("Bad Request!!");
}
}
else System.out.println("Request Error!!");
}
}catch (Exception e){

}
}
}.start();

}catch (Exception e){

}
}
}
66 changes: 66 additions & 0 deletions 2020 Computer Networks/Project/WebServer/Connection.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Connection extends Thread{
// Required variables for i/o operations..
Socket socket;
PrintWriter printWriter;
BufferedReader bufferedReader;
OutputStream outputStream;
boolean isValid=true; // for validation of requests..
public Connection(Socket socket) throws Exception { // Connection constuct for initialize variables..

this.socket=socket;
InputStreamReader inputStreamReader=new InputStreamReader(this.socket.getInputStream());
bufferedReader=new BufferedReader(inputStreamReader);
printWriter=new PrintWriter(this.socket.getOutputStream());
outputStream=socket.getOutputStream();
}
public void run(){ // Thread start..

try {
String requestFrame=""; // Holds the request that comes from client..
while (bufferedReader.ready() || requestFrame.length()==0){
requestFrame+=(char)bufferedReader.read(); // reads buffer char by char to get all the request..
}
HTTPRequest request = new HTTPRequest(requestFrame);
if (!request.fileReq.matches("^[0-9]*$") || Integer.parseInt(request.fileReq) > 20000 || Integer.parseInt(request.fileReq) < 100) {// file size and isDigit check..
HTTPResponse errorResponse = new HTTPResponse(request);
System.out.println(errorResponse.HTTPBadRequestResponse(request));
isValid = false;
}
if (request.methodName.equals("TRACE") || request.methodName.equals("HEAD") || request.methodName.equals("POST") || request.methodName.equals("PUT") || request.methodName.equals("DELETE")) {
HTTPResponse errorResponse = new HTTPResponse(request);
System.out.println(errorResponse.HTTPNotImplementedResponse(request));
isValid = false;
}
if (isValid && request.methodName.equals("GET")) { // if the request is valid and it is a GET method then the request, the response write to the console and browser.
framePrinter(requestFrame);
HTTPResponse response = new HTTPResponse(request);
streamPrinter(outputStream,response);
printWriter.close();
bufferedReader.close();
socket.close();
}
} catch (Exception e) {

}
}
public void framePrinter(String requestFrame){ // prints request
System.out.println("----Start of Request Frame----\n");
System.out.print(requestFrame);
System.out.println("\n----End of Request Frame----\n");
}
public void streamPrinter(OutputStream outputStream,HTTPResponse response){ // prints response to the browser..
try {
outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
outputStream.write("\r\n".getBytes());
outputStream.write(response.response.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
}catch (Exception e){

}
}
}
14 changes: 14 additions & 0 deletions 2020 Computer Networks/Project/WebServer/HTTPRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
public class HTTPRequest {
String methodName; // method name of the request
String fileReq; // size of file
public HTTPRequest(String request) {
String[] lines = request.split("\n");
try {
methodName=lines[0].split(" ")[0];
fileReq = lines[0].split(" ")[1];
fileReq = fileReq.substring(1);
}catch (Exception e){

}
}
}
46 changes: 46 additions & 0 deletions 2020 Computer Networks/Project/WebServer/HTTPResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//import java.io.*;
//import java.net.http.HttpResponse;
public class HTTPResponse { // response class for create the respnse
HTTPRequest request;
String response;
String alphabet="abcdefghijklmnopqrstuvwxyz"; // alphabet for creating the html document..
String CRLF = " \r\n";
String htmlTags="<html><head><title>title</title></head><body>";
String htmlClosingTags="</body></html>"+CRLF;
String consoleResponse; // for print response to the console..
public HTTPResponse(HTTPRequest request) {
this.request = request;
try {
response =htmlTags;
int size=Integer.parseInt(request.fileReq);
for (int i=0;i<size-62;i++){
response+=alphabet.charAt((int)(Math.random()*(26)));
}// in that part, total count of chars in html tags is 59 so for example 1000 is requested size ...
// 1000 - 59 = 941. The for loop iterates 941 times and creates 941 random chars for html file. As a result..
// of that operation we have a html file that is exactly 1000 bytes..
response+=htmlClosingTags;
if (size>=100 && size<=20000) { // if size is between 100 and 20000 so the console output is created.
consoleResponse = "Server: Multi-Threaded Web Server" + CRLF;
consoleResponse = consoleResponse + "Content-Type: text/html" + CRLF;
consoleResponse = consoleResponse + "Connection: keep-alive" + CRLF;
consoleResponse = consoleResponse + "Content-Length: " + response.length() + CRLF;
System.out.print(consoleResponse);
System.out.println("----Contents of the request----");
System.out.println(response);
System.out.println("\n----Contents of the requested file---- Ended.");
}
}catch (Exception e){ // exception for response..
System.out.println("Response Error!!!");
}
}
public String HTTPBadRequestResponse(HTTPRequest request){ // response for invalid requests..
this.request=request;
response="400 Bad Request"+CRLF;
return response;
}
public String HTTPNotImplementedResponse(HTTPRequest request){ // response for not implemented requests.
this.request=request;
response="501 Not Implemented"+CRLF;
return response;
}
}
52 changes: 52 additions & 0 deletions 2020 Computer Networks/Project/WebServer/WebServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Java HTTP Web Server Implementation
// Abdullah Gülçür - 150116014
// Enes Garip - 150116034

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {
ServerSocket server_socket;
static int portNumber;

public static void main(String[] args) throws Exception {
if (args.length != 1 || !args[0].matches("^[0-9]*$")) {

System.out.println("Argument Error!!!");
}
else {
portNumber=Integer.parseInt(args[0]);
System.out.println("Port Number: " + portNumber);
WebServer webServer=new WebServer();
webServer.runServer();
}
}

public void runServer() throws Exception {

System.out.println("Web Server has started now.");
server_socket = new ServerSocket(portNumber); // New server socket. The port is the argument of the program.
processHTTPRequest();
}

public void processHTTPRequest() {
// For multithreading there is an infinite loop that creates sockets for each client..
while(true) {
System.out.println("Connection established on port: " + portNumber);
Socket socket = null;
try {
socket = server_socket.accept(); // Accept the requests of the clients..
} catch (IOException e) {
e.printStackTrace();
}
Connection connection = null;
try {
connection = new Connection(socket); // Connection object created. In Connection class, the server begins to work with request and responses.
} catch (Exception e) {
e.printStackTrace();
}
connection.start(); // The connection class extends Threads so the multithreading process begins..
}
}
}
Binary file not shown.
Loading

0 comments on commit a5cec2b

Please sign in to comment.