/************Form1.cs************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; namespace IISTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public delegate void MyInvoke(string str1);//要用一个delegate来Invoke public void FormMessage(string msg) { richTextBox1.AppendText(msg + "\n"); } private string getContentType(string Extension) //自动获取ContentType { if (!Extension.StartsWith(".")) { return ""; //不是扩展名 } string regValue = ""; try { Microsoft.Win32.RegistryKey rk1, rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\MIME\Database\Content Type"); //这一句的意思是:声明两个RegistryKey,一个是rk1,没有赋值,另外一个rk,赋值为后面的值。 foreach (string s in rk.GetSubKeyNames()) { rk1 = rk.OpenSubKey(s); regValue = (string)rk1.GetValue("Extension"); if (regValue == Extension) {
{
public Form1()
{
InitializeComponent();
} public void SHow()
{
this.tbIp.Text = "192.168.19.17";
this.tbShu.Text = "8080"; TcpClient client = new TcpClient("192.168.19.17",8080);
NetworkStream stream = client.GetStream();
StreamWriter sw = new StreamWriter(stream, Encoding.Default);
string readline = Console.ReadLine();
this.textBox1.Text = readline;
}
private void butconnect_Click(object sender, EventArgs e)
{
Thread th = new Thread(SHow);
th.Start(); }
}
Hi.baidu.com/lyf610400210
2012-07-27 11:03 [非CV]C#模拟Http服务器源码
//杜绝一切直接^C+^V行为!
//这是一段根据网上CV了很久的一段代码的改编版本
//这也算是一种创新吧——LYF
/************Form1.cs************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace IISTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void MyInvoke(string str1);//要用一个delegate来Invoke
public void FormMessage(string msg)
{
richTextBox1.AppendText(msg + "\n");
}
private string getContentType(string Extension) //自动获取ContentType
{
if (!Extension.StartsWith("."))
{
return ""; //不是扩展名
}
string regValue = "";
try
{
Microsoft.Win32.RegistryKey rk1, rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\MIME\Database\Content Type");
//这一句的意思是:声明两个RegistryKey,一个是rk1,没有赋值,另外一个rk,赋值为后面的值。
foreach (string s in rk.GetSubKeyNames())
{
rk1 = rk.OpenSubKey(s);
regValue = (string)rk1.GetValue("Extension");
if (regValue == Extension)
{
return s;
}
}
return "";
}
catch
{
return "";
}
}
private void Form1_Load(object sender, EventArgs e)
{
if (!HttpListener.IsSupported)
{
MessageBox.Show("系统版本太低!至少Windows XP SP2!","",MessageBoxButtons.OK,MessageBoxIcon.Stop);//现在这种情况很少见
Application.Exit();
}
}
public static string wwwroot = "C:\\Inetpub\\wwwroot";//这是WWWRoot,可以更改
public static string indexpage = "index.html"; //这是默认页,可以更改
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
MyInvoke mi = new MyInvoke(FormMessage);
using (HttpListener listerner = new HttpListener())
{
listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous; //指定身份验证 Anonymous匿名访问
listerner.Prefixes.Add("http://+:80/");
listerner.Start();
this.BeginInvoke(mi, new object[] { "WebServer Starts Successfully......." });
while (true)
{
//等待请求连接
//没有请求则GetContext处于阻塞状态
HttpListenerContext ctx = listerner.GetContext();
ctx.Response.StatusCode = 200; //设置返回给客服端http状态代码,200:一切正常
if (backgroundWorker1.CancellationPending)
{ //如果停止了
//WebClient a = new WebClient();
break;
}
/*
string file = ctx.Request.QueryString["file"];
string vid = ctx.Request.QueryString["vid"];
string id = ctx.Request.QueryString["id"];//这是获取不同Query参数值的方法之一
if (file != null)
{
this.BeginInvoke(mi, new object[] { "Query: file="+file });
}
* */
this.BeginInvoke(mi, new object[] { "Query: " + ctx.Request.Url.Query });
this.BeginInvoke(mi, new object[] { "URL: " + ctx.Request.Url.ToString() + "\nHost: " + ctx.Request.Url.Host + "\nLocalPath: " + ctx.Request.Url.LocalPath });
//使用Writer输出http响应代码
StreamWriter writer = new StreamWriter(ctx.Response.OutputStream);
FileStream LocalFileStream;
if (ctx.Request.Url.LocalPath == "/")
{
//加载首页
try
{
LocalFileStream = new FileStream(wwwroot + "\\" + indexpage, FileMode.Open);
}
catch (Exception e1)
{
this.BeginInvoke(mi, new object[] { "Load " + wwwroot + "\\" + indexpage + " Failed: " + e1.Message });
LocalFileStream = new FileStream(Application.StartupPath + "\\error.html", FileMode.Open);
}
}
else
{
try
{
LocalFileStream = new FileStream(wwwroot + ctx.Request.Url.LocalPath.Replace('/', '\\'), FileMode.Open);
}
catch (Exception e2)
{
this.BeginInvoke(mi, new object[] { "Load " + wwwroot + ctx.Request.Url.LocalPath.Replace('/', '\\') + " Failed: " + e2.Message });
LocalFileStream = new FileStream(Application.StartupPath + "\\error.html", FileMode.Open);
}
}
response.ContentType = getContentType(new FileInfo(LocalFileStream.Name).Extension);
byte[] Tempbytes;
BinaryReader LocalFileReader = new BinaryReader(LocalFileStream);
BinaryWriter bw = new BinaryWriter(ctx.Response.OutputStream);
while (LocalFileStream.Position < LocalFileStream.Length)
{
Tempbytes = LocalFileReader.ReadBytes(9216);
//这里LocalFileStream.Position的值变为9216
//this.BeginInvoke(mi, new object[] { (LocalFileStream.Position / LocalFileStream.Length*100).ToString() });
bw.Write(Tempbytes); //写值
}
this.BeginInvoke(mi, new object[] { "File Download%: " + LocalFileStream.Position.ToString() + "/" + LocalFileStream.Length.ToString() + "\n" });
bw.Close();
LocalFileReader.Close();
LocalFileStream.Close();
ctx.Response.Close();
}
listerner.Stop();
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MyInvoke mi = new MyInvoke(FormMessage);
this.BeginInvoke(mi, new object[] { "WebServer Stopped." });
}
private void button1_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
else
{
MessageBox.Show("正忙");
}
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
}
}
if (contentLength > 0)
{
int bytesRecd = 0;
while (bytesRecd < contentLength)
{
byte[] bytes = new byte[BUFSZ];
int bytesNowGot = s.Receive(bytes);
for(int i = 0 ; i < bytesNowGot; i++)
{
ResponseBytesList.Add(bytes[i]);
}
bytesRecd += bytesNowGot;
data += System.Text.Encoding.UTF8.GetString(bytes, 0, bytesNowGot);
}
}
else
{
int bytesNowGot = 0;
do
{
byte[] bytes = new byte[BUFSZ];
bytesNowGot = s.Receive(bytes);
for (int i = 0; i < bytesNowGot; i++)
{
ResponseBytesList.Add(bytes[i]);
}
data += System.Text.Encoding.UTF8.GetString(bytes, 0, bytesNowGot);
} while (bytesNowGot > 0);
}
//ResponseBytes = utf8.GetBytes(data);
ResponseBytes = ResponseBytesList.ToArray();
clientSock.Send(ResponseBytes);