単一ファイルサーバ(『javaネットワークプログラミング』より抜粋)
3040 ワード
ackage net.programe.ten;
import java.io.*;
import java.net.*;
/**
* http ,
*
* @author Arthur
*/
public class SingleFileHttpServer extends Thread {
//
private byte[] content;
//
private byte[] header;
// 80
private int port = 80;
public SingleFileHttpServer(String data, String encoding, String MIMEType, int port)
throws UnsupportedEncodingException {
this(data.getBytes(encoding), encoding, MIMEType, port);
}
public SingleFileHttpServer(byte[] data, String encoding, String MIMEType, int port)
throws UnsupportedEncodingException {
this.content = data;
this.port = port;
String header = "HTTP/1.0 200 OK\r
"
+ "Server:OneFile 1.0\r
"
+ "Content-length:" + this.content.length + "\r
"
+ "Content-type" + MIMEType + "\r
\r
";
this.header = header.getBytes("ASCII");
}
@Override
public void run() {
try {
// socket
ServerSocket server = new ServerSocket(this.port);
System.out.println(" " + server.getLocalPort() + " ");
while (true) {
Socket conn = null;
try {
conn = server.accept();
// ,
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
// ,
InputStream in = new BufferedInputStream(conn.getInputStream());
// , 80
StringBuffer request = new StringBuffer(80);
//
while (true) {
//
int c = in.read();
if (c == '\r' || c == '
' || c == -1) {
break;
}
request.append((char) c);
}//end while
// HTTP/1.0 , MIME
if (request.toString().indexOf("HTTP/") != -1) {
//
out.write(this.header);
}
// context
out.write(content);
//
out.flush();
} catch (IOException ex) {
}
}//end while
} catch (IOException ex) {
ex.printStackTrace();
}
}//end run
public static void main(String[] args) throws UnsupportedEncodingException {
String encoding = "ASCII";
byte content[] = "hello java net".getBytes(encoding);
Thread t = new SingleFileHttpServer(content, encoding, "text/html", 80);
t.start();
}
}