首页 > 开发 > 综合 > 正文

用浏览器来接收C# 的程序返回的时间

2024-07-21 02:27:32
字体:
来源:转载
供稿:网友

今天早上 我写了一篇 用socket 做的 时间服务器,当时我说准备用一段时间作个不需要客户端接收数据
而是用 浏览器 接收数据的程序,很顺利,一天的时间 我就做好了:)
闲话不说,先看程序。。。

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;
}
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表