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\n" + "Server:OneFile 1.0\r\n" + "Content-length:" + this.content.length + "\r\n" + "Content-type" + MIMEType + "\r\n\r\n"; 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 == '\n' || 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(); }}