System.Uri ms = new Uri("http://www.microsoft.com/en/us/default.aspx");
Console.WriteLine("Scheme: {0}", ms.Scheme);
Console.WriteLine("Host: {0}", ms.Host);
Console.WriteLine("Port: {0}", ms.Port);
Console.WriteLine("AbsolutePath: {0}", ms.AbsolutePath);
Console.WriteLine("Query: {0}", ms.Query);
Console.ReadKey();
public void Run()
{
// 取得本机的 loopback 网络地址,即 127.0.0.1
IPAddress address = IPAddress.Loopback;
// 创建可以访问的端点,49152 表示端口号
IPEndPoint endPoint = new IPEndPoint(address, 49152);
// 创建一个 socket,使用 IPv4 地址,传输控制协议 TCP,双向、可靠、基于连接的字节流
Socket socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// 将 socket 绑定到一个端点上
socket.Bind(endPoint);
// 设置连接队列的长度
socket.Listen(10);
Console.WriteLine("开始监听, 端口号:{0}.", endPoint.Port);
while (true)
{
// 开始监听,这个方法会阻塞线程的执行,直到接受到一个客户端的连接请求
Socket client = socket.Accept();
// 输出客户端的地址
Console.WriteLine(client.RemoteEndPoint);
// 准备读取客户端请求的数据,读取的数据将保存在一个数组中
byte[] buffer = new byte[4096];
// 接受数据
int length = client.Receive(buffer, 4096, SocketFlags.None);
// 将请求的数据翻译为 UTF-8
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
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>From Socket Server</title></head>
<body><h1>Hello, world.</h1></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);
// 向客户端发送状态信息
client.Send(statusLineBytes);
// 向客户端发送回应头
client.Send(responseHeaderBytes);
// 头部与内容的分隔行
client.Send(new byte[] { 13, 10 });
// 向客户端发送内容部分
client.Send(responseBodyBytes);
// 断开与客户端的连接
client.Close();
if (Console.KeyAvailable)
break;
}
// 关闭服务器
socket.Close();
}
public void Run()
{
// 取得本机的 loopback 网络地址,即 127.0.0.1
IPAddress address = IPAddress.Loopback;
// 创建可以访问的端点,49152 表示端口号
IPEndPoint endPoint = new IPEndPoint(address, 49152);
// 创建 TCP 监听器
TcpListener newserver = new TcpListener(endPoint);
// 启动监听器
newserver.Start();
Console.WriteLine("开始监听...");
while (true)
{
// 等待客户端连接
TcpClient newclient = newserver.AcceptTcpClient();
Console.WriteLine("已经建立连接!");
// 得到一个网络流
NetworkStream ns = newclient.GetStream();
// 处理过程中使用 UTF-8 编码
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
byte[] request = new byte[4096];
int length = ns.Read(request, 0, 4096);
string requestString = utf8.GetString(request, 0, length);
Console.WriteLine(requestString);
// 状态行
string statusLine = "HTTP/1.1 200 OK\r\n";
byte[] statusLineBytes = utf8.GetBytes(statusLine);
// 准备发送到客户端的网页
string responseBody
= @"<html>
<head><title>From TcpListener Server</title></head>
<body><h1>Hello, world.</h1></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();
}
public void Run()
{
// 检查系统是否支持
if (!HttpListener.IsSupported)
{
throw new System.InvalidOperationException(
"使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
}
// 注意前缀必须以 / 正斜杠结尾
string[] prefixes = new string[] { "http://localhost:49152/" };
// 创建监听器.
HttpListener listener = new HttpListener();
// 增加监听的前缀.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
// 开始监听
listener.Start();
Console.WriteLine("监听中...");
while (true)
{
// 注意: GetContext 方法将阻塞线程,直到请求到达
HttpListenerContext context = listener.GetContext();
// 取得请求对象
HttpListenerRequest request = context.Request;
Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes));
Console.WriteLine("Accept-Language: {0}",
string.Join(",", request.UserLanguages));
Console.WriteLine("User-Agent: {0}", request.UserAgent);
Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
Console.WriteLine("Connection: {0}",
request.KeepAlive ? "Keep-Alive" : "close");
Console.WriteLine("Host: {0}", request.UserHostName);
Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);
// 取得回应对象
HttpListenerResponse response = context.Response;
// 构造回应内容
string responseString
= @"<html>
<head><title>From HttpListener Server</title></head>
<body><h1>Hello, world.</h1></body>
</html>";
// 设置回应头部内容,长度,编码
response.ContentLength64
= System.Text.Encoding.UTF8.GetByteCount(responseString);
response.ContentType = "text/html; charset=UTF-8";
// 输出回应内容
System.IO.Stream output = response.OutputStream;
System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
writer.Write(responseString);
// 必须关闭输出流
writer.Close();
if (Console.KeyAvailable)
break;
}
// 关闭服务器
listener.Stop();
}