一,新建一个项目TestWeb,项目类型:Windows窗口应用程序。
二,新建类RequestProcessor。
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace TestWeb
{
class RequestProcessor
{
public bool ParseRequestAndProcess(string[] RequestLines)//解析内容
{
for (int i = 0; i < RequestLines.Length; i++)
System.Diagnostics.Trace.Write(RequestLines[i]);
三,新建类ClientSocketThread。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TestWeb
{
class ClientSocketThread
{
public TcpListener tcpl;//Notice: get from SrvMain.tcpl
private static Encoding ASCII = Encoding.ASCII;
public void HandleThread()
{
Thread currentThread = Thread.CurrentThread;
try
{
Socket s = tcpl.AcceptSocket();
RequestProcessor aRequestProcessor = new RequestProcessor(); //Notice:
aRequestProcessor.mSockSendData = s;//Notice: so that the processor can work
const int BUFFERSIZE = 4096;//that‘s enough???
Byte[] readclientchar = new Byte[BUFFERSIZE];
char[] sps = new Char[2] { ‘\r‘, ‘\n‘ };
string[] RequestLines = new string[32];
do
{
//use BUFFERSIZE contral the receive data size to avoid the BufferOverflow attack
int rc = s.Receive(readclientchar, 0, BUFFERSIZE, SocketFlags.None);
} while (aRequestProcessor.ParseRequestAndProcess(RequestLines));
s.Close();
}
catch (SocketException)
{
}
}
}
}
四,主对话框中增加按钮,按键的相应函数加如下代码。
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;
using System.Threading;
namespace TestWeb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//启动监听程序
TcpListener tcpl;
IPAddress LocalIP = Dns.Resolve("localhost").AddressList[0];
tcpl = new TcpListener(LocalIP, 80); // listen on port 80
tcpl.Start();
// int ThreadID = 0;
while (true)
{
while (!tcpl.Pending())
{
Thread.Sleep(100);
}
//启动接受线程
ClientSocketThread myThreadHandler = new ClientSocketThread();
myThreadHandler.tcpl = tcpl;//Notice: dont forget do this
ThreadStart myThreadStart = new ThreadStart(myThreadHandler.HandleThread);
Thread myWorkerThread = new Thread(myThreadStart);
myWorkerThread.Start();
}
}
catch (SocketException )
{