您的位置:首页 > 理论基础 > 计算机网络

读书笔记-最简单的web服务器:网络插座Socket

2012-05-01 16:56 483 查看
消息的格式:



直接上代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace SimpleSocketServer
{
class Program
{
static void Main(string[] args)
{
// 获取本机的Loopback 网络地址 如:127.0.0.1
IPAddress address = IPAddress.Loopback;
// 创建可访问的端点,49152表示端口号,如果设置为0 则表示设置一个空闲的端口
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);
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
// 把数据类型转化为UTF-8
string requestring = utf8.GetString(buffer);

// 显示客户端的响应
Console.WriteLine(requestring);

// 回应的状态行
string statusline = "HTTP/1.1 200 OK\r\n";
byte[] statuslinebytes = utf8.GetBytes(statusline);
// 发送到客户端的网页
string requestHtml = "<html><head><title>测试</title></head><body><h1>您好!</h1></body></html>";
byte[] requestHtmlbytes = utf8.GetBytes(requestHtml);
// 回应的头部 这里Content-Length的长度要用Byte的长度,不然如果内容有汉字的话显示会不正常
string responseHead = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length: {0}\r\n", requestHtmlbytes.Length);
byte[] responseHeadBytes = utf8.GetBytes(responseHead);
// 向客户端发送状态信息
client.Send(statuslinebytes);
// 向客户端发送回应头
client.Send(responseHeadBytes);
// 头部和内容分隔行
client.Send(new byte[] { 13,10});
// 向客户端发送内容部分
client.Send(requestHtmlbytes);
// 端口客户端的连接
client.Close();
if (Console.KeyAvailable)
{
break;
}
}

socket.Close();
}
}
}


访问地址:

http://127.0.0.1:49152/

效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: