Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class Server {
- private static int PORT = 4333;
- private ServerSocket serverSocket;
- ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
- public static void main(String[] args) {
- try {
- System.out.println("n====================Server Details====================");
- System.out.println("Server Machine: "+ InetAddress.getLocalHost().getCanonicalHostName());
- System.out.println("Port number: " + PORT);
- } catch (UnknownHostException e1) {
- e1.printStackTrace();
- }
- try {
- Server server = new Server();
- server.start();
- } catch (IOException e) {
- System.err.println("Error occured:" + e.getMessage());
- System.exit(0);
- }
- }
- public Server() throws IOException {
- serverSocket = new ServerSocket(PORT);
- }
- private void start() throws IOException {
- System.out.println("----- Started Blocking Server -----");
- while (true) {
- Socket socket = serverSocket.accept();
- HttpHandler connection = new HttpHandler(socket);
- executorService.submit(connection);
- }
- }
- }
- import handler.CPUHandler;
- import handler.DBHandler;
- import handler.IOHandler;
- import handler.MemoryHandler;
- import parser.GetRequestParser;
- import java.io.*;
- import java.net.Socket;
- import java.util.Dictionary;
- public class HttpHandler implements Runnable {
- private Socket socket;
- public HttpHandler(Socket socket) {
- this.socket = socket;
- }
- public void run() {
- try {
- handleRequest();
- } catch (Exception e) {
- System.err.println("Error Occured: " + e.getMessage());
- try {
- socket.close();
- System.exit(0);
- } catch (IOException e1) {
- System.err.println("Error Closing socket Connection.");
- System.exit(0);
- }
- System.err.println("Server is Terminating!");
- }
- }
- private void handleRequest() throws Exception {
- InputStream input;
- OutputStream output;
- input = socket.getInputStream();
- output = socket.getOutputStream();
- serverRequest(input, output);
- output.close();
- input.close();
- socket.close();
- }
- private void serverRequest(InputStream input, OutputStream output) throws Exception {
- String line;
- BufferedReader bf = new BufferedReader(new InputStreamReader(input));
- while ((line = bf.readLine()) != null) {
- if (line.length() <= 0) {
- break;
- }
- if (line.startsWith("GET")) {
- // read the request and write the response to output
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement