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();
}
}
一个单文件服务器(摘自《java网络编程》)
关注
打赏