Created
December 21, 2012 16:10
-
-
Save lrlucena/4353726 to your computer and use it in GitHub Desktop.
Servidor HTTP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
public class ServidorHttp { | |
public static void main(String args[]) { | |
ServerSocket s = null; | |
try { | |
s = new ServerSocket(7896); | |
// right now the stream is open. | |
while (true) { | |
Socket clientSocket = s.accept(); | |
new Connection(clientSocket); | |
// now the connection is established | |
} | |
} catch (IOException e) { | |
System.out.println("Unable to read: " + e.getMessage()); | |
} | |
} | |
} | |
class Connection extends Thread { | |
Socket clientSocket; | |
BufferedReader din; | |
OutputStreamWriter outWriter; | |
public Connection(Socket clientSocket) { | |
try { | |
this.clientSocket = clientSocket; | |
din = new BufferedReader(new InputStreamReader( | |
clientSocket.getInputStream(), "ASCII")); | |
outWriter = new OutputStreamWriter(clientSocket.getOutputStream()); | |
this.start(); | |
} catch (IOException e) { | |
System.out.println("Connection: " + e.getMessage()); | |
} | |
} | |
public void run() { | |
try { | |
String line = null; | |
String s = ""; | |
while ((line = din.readLine()) != null) { | |
s = s +"\r\n"+ line; | |
System.out.println("Read " + line); | |
if (line.length() == 0) | |
break; | |
} | |
// here write the content type etc details: | |
System.out.println("Someone connected: " + clientSocket); | |
outWriter.write("HTTP/1.1 200 OK\r\n"); | |
outWriter.write("Date: Tue, 11 Jan 2011 13:09:20 GMT\r\n"); | |
outWriter.write("Expires: -1\r\n"); | |
outWriter.write("Cache-Control: private, max-age=0\r\n"); | |
outWriter.write("Content-type: text/html\r\n"); | |
outWriter.write("Server: vinit\r\n"); | |
outWriter.write("X-XSS-Protection: 1; mode=block\r\n\r\n"); | |
outWriter | |
.write("<html><head><title>Servidor HTTP</title></head><body><h1>Pedido recebido do Cliente</h1><pre>"+s+"</pre></body></html>\r\n"); | |
} catch (EOFException e) { | |
System.out.println("EOF: " + e.getMessage()); | |
} catch (IOException e) { | |
System.out.println("IO at run: " + e.getMessage()); | |
} finally { | |
try { | |
outWriter.close(); | |
clientSocket.close(); | |
} catch (IOException e) { | |
System.out.println("Unable to close the socket"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment