今天早上 我寫了一篇 用socket 做的 時間服務(wù)器,當(dāng)時我說準(zhǔn)備用一段時間作個不需要客戶端接收數(shù)據(jù)
而是用 瀏覽器 接收數(shù)據(jù)的程序,很順利,一天的時間 我就做好了:)
閑話不說,先看程序。。。
using system;
using system.collections;
using system.io;
using system.net;
using system.net.sockets;
using system.threading;
class httpprocessor {
private socket s;
private bufferedstream bs;
private streamreader sr;
private streamwriter sw;
private string method;
private string url;
private string protocol;
private hashtable hashtable;
public httpprocessor(socket s) {
this.s = s;
hashtable = new hashtable();
}
public void process() {
networkstream ns = new networkstream(s, fileaccess.readwrite);
bs = new bufferedstream(ns);
sr = new streamreader(bs);
sw = new streamwriter(bs);
writeurl();
s.shutdown(socketshutdown.sdboth);
ns.close();
}
public void writeurl() {
try {
writesuccess();
} catch(filenotfoundexception) {
writefailure();
sw.writeline("file not found: " + url);
}
sw.flush();
}
public void writesuccess() {
sw.writeline("http/1.1 200 ok");
sw.writeline("server: microsoft-iis/5.0");
sw.writeline("date: mon, 27 nov 2000 08:19:43 gmt");
sw.writeline("content-length: 6");
sw.writeline("content-type: text/html");
sw.writeline("");
string strdateline;
datetime now;
now = datetime.now;
strdateline = now.toshortdatestring() + " " + now.tolongtimestring();
sw.writeline(strdateline);
}
public void writefailure() {
sw.writeline("http/1.0 404 file not found");
sw.writeline("connection: close");
sw.writeline();
}
}
public class httpserver {
public httpserver() : this(81) {
}
public httpserver(int port) {
this.port = port;
}
public void listen() {
socket listener = new socket(0, sockettype.sockstream, protocoltype.prottcp);
ipaddress ipaddress = new ipaddress("169.254.0.244");
ipendpoint endpoint = new ipendpoint(ipaddress, port);
listener.bind(endpoint);
listener.blocking = true;
listener.listen(-1);
console.writeline("press ctrl+c to quit...");
while(true) {
socket s = listener.accept();
httpprocessor processor = new httpprocessor(s);
thread thread = new thread(new threadstart(processor.process));
thread.start();
}
}
public static int main(string[] args) {
httpserver httpserver;
if(args.getlength(0) > 0) {
httpserver = new httpserver(args[0].touint16());
} else {
httpserver = new httpserver();
}
thread thread = new thread(new threadstart(httpserver.listen));
thread.start();
return 0;
}
}
新聞熱點
疑難解答
圖片精選