You are on page 1of 2

import java.io.*; import java.net.*; import java.util.

*; public class ServidorWebParcial { public static void main(String[] args) throws Exception{ String requestMessageLine; String fileName; ServerSocket listenSocket = new ServerSocket(80); Socket connectionSocket = listenSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStream Reader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSo cket.getOutputStream()); requestMessageLine = inFromClient.readLine(); StringTokenizer tokenizedLine = new StringTokenizer(requestMessa geLine); if(tokenizedLine.nextToken().equals("GET")){ fileName = tokenizedLine.nextToken(); if(fileName.startsWith("/")) fileName = fileName.substring(1); File file = new File(fileName); if(file.exists()){ int numOfBytes = (int) file.length();

FileInputStream inFile = new FileInputStream(fil eName); byte[] fileInBytes = new byte[numOfBytes]; inFile.read(fileInBytes); outToClient.writeBytes("HTTP/1.0 200 OK\r\n"); outToClient.writeBytes("Content-Language: pt-BR\ r\n");

if(fileName.endsWith(".html")){ outToClient.writeBytes("Content-Type: te xt/html\r\n"); } if(fileName.endsWith(".png")){ outToClient.writeBytes("Content-Type: im age/png\r\n"); } outToClient.writeBytes("Content-Length: "+numOfB ytes+"\r\n"); outToClient.writeBytes("\r\n");

outToClient.write(fileInBytes,0,numOfBytes); } else{ outToClient.writeBytes("HTTP/1.0 404 Not Found\r \n"); } } connectionSocket.close(); }

You might also like