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

来源:互联网 责任编辑:栏目编辑 发表时间:2013-07-02 05:37 点击:

今天早上 我写了一篇 用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;
}
}

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • 用C#制作屏幕捕获程序
  • .NET程序员项目开发必知必会—Dev环境中的集成测试用例执行时上
  • 遍历ArrayList易犯错误
  • C#对XML操作:一个处理XML文件的类(1)
  • .NET简谈反射(动态调用)
  • 使用C#编写LED样式时钟控件
  • DataList嵌套问题 如何删除内层子DataList的记录
  • 怎样用C#实现完整文档打印功能
  • .NET简谈自定义事务资源管理器
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1