程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 用浏覽器來接收C# 的程序返回的時間

用浏覽器來接收C# 的程序返回的時間

編輯:關於C語言

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved