uni

University stuff
git clone git://git.margiolis.net/uni.git
Log | Files | Refs | README | LICENSE

HTTPServer.java (1144B)


      1 import java.io.*;
      2 import java.net.*;
      3 
      4 class SocketUtils {
      5 	static final int BUF_LEN = 1024;
      6 
      7 	public static String getRequest(Socket sock) throws Exception {
      8 		StringBuilder reqstr = new StringBuilder();
      9 		byte[] reqbytes = new byte[BUF_LEN];
     10 		InputStream in = sock.getInputStream();
     11 		int n;
     12 
     13 		while (true) {
     14 			n = in.read(reqbytes, 0, BUF_LEN);
     15 			if (n == -1)
     16 				break;
     17 			reqstr.append(new String(reqbytes, 0, n));
     18 			if (n < BUF_LEN)
     19 				break;
     20 		}
     21 		return reqstr.toString();
     22 	}
     23 }
     24 
     25 public class HTTPServer {
     26 	public static void main(String[] args) throws Exception {
     27 		ServerSocket srvsock = new ServerSocket(8010);
     28 		Socket sock;
     29 		String req;
     30 		PrintWriter pw;
     31 
     32 		while (true) {
     33 			System.out.println("[HTTPServer] waiting for client");
     34 			sock = srvsock.accept();
     35 			req = SocketUtils.getRequest(sock);
     36 			System.out.println("[HTTPServer] obtained request:\n\n" + req);
     37 			pw = new PrintWriter(sock.getOutputStream());
     38 
     39 			pw.println("HTTP/1.0 200 OK");
     40 			pw.println("Content-type: text/html");
     41 			pw.println("Server: Java 6.1\n");
     42 
     43 			pw.println("<html><body>Hello world</body></html>");
     44 			pw.close();
     45 			sock.close();
     46 		}
     47 	}
     48 }