简单的基于TcpListener的Web服务器实例
1.新建控制台工程,代码如下
static void Main(string[] args)
{
IPAddress address = IPAddress.Loopback;
IPEndPoint endPoint = new IPEndPoint(address, 50000);
TcpListener newServer = new TcpListener(endPoint);
newServer.Start(10);
Console.WriteLine("开始监听。。。");
while (true)
{
TcpClient newClient = newServer.AcceptTcpClient();
Console.WriteLine("建立了一个连接");
NetworkStream ns = newClient.GetStream();
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
byte [] buffer = new byte [4096];
int length = ns.Read(buffer, 0, 4096);
string requestString = utf8.GetString(buffer, 0, length); // 接收请求信息
Console.WriteLine(requestString);
// 发送响应信息
string statusLine = "HTTP/1.1 200 OK\r\n";
byte[] statusLineBytes = utf8.GetBytes(statusLine); // 状态行
string responseBody = "<html><head><title>response server</title></head><body>hello world!</body></html>";
byte[] responseBodyBytes = utf8.GetBytes(responseBody);// 内容部分
string responseHeader = String.Format("Content-Type: text/html;charset=UTF-8\r\nContent-Length:{0}\r\n",
responseBody.Length);
byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);// 回应头
//输出回应信息
ns.Write(statusLineBytes,0, statusLineBytes.Length);
ns.Write(responseHeaderBytes, 0, responseHeaderBytes.Length);
ns.Write(new byte[] { 13, 10 }, 0, 2);
ns.Write(responseBodyBytes, 0, responseBodyBytes.Length);
newClient.Close();
if (Console.KeyAvailable)
{
break;
}
}
newServer.Stop();
}
static void Main(string[] args)
{
IPAddress address = IPAddress.Loopback;
IPEndPoint endPoint = new IPEndPoint(address, 50000);
TcpListener newServer = new TcpListener(endPoint);
newServer.Start(10);
Console.WriteLine("开始监听。。。");
while (true)
{
TcpClient newClient = newServer.AcceptTcpClient();
Console.WriteLine("建立了一个连接");
NetworkStream ns = newClient.GetStream();
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
byte [] buffer = new byte [4096];
int length = ns.Read(buffer, 0, 4096);
string requestString = utf8.GetString(buffer, 0, length); // 接收请求信息
Console.WriteLine(requestString);
// 发送响应信息
string statusLine = "HTTP/1.1 200 OK\r\n";
byte[] statusLineBytes = utf8.GetBytes(statusLine); // 状态行
string responseBody = "<html><head><title>response server</title></head><body>hello world!</body></html>";
byte[] responseBodyBytes = utf8.GetBytes(responseBody);// 内容部分
string responseHeader = String.Format("Content-Type: text/html;charset=UTF-8\r\nContent-Length:{0}\r\n",
responseBody.Length);
byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);// 回应头
//输出回应信息 www.2cto.com
ns.Write(statusLineBytes,0, statusLineBytes.Length);
ns.Write(responseHeaderBytes, 0, responseHeaderBytes.Length);
ns.Write(new byte[] { 13, 10 }, 0, 2);
ns.Write(responseBodyBytes, 0, responseBodyBytes.Length);
newClient.Close();
if (Console.KeyAvailable)
{
break;
}
}
newServer.Stop();
}
2.运行该工程
3.效果图如下
摘自 hi_dzj的专栏
相关新闻>>
- 发表评论
-
- 最新评论 更多>>