.NET网络编程学习(二) (续)

.NET网络编程学习(二) (续)

良好的可伸缩性,良好的性能是对Http服务器的基本要求,我们把上一节中的一个简单的Http服务器程序进行扩展,使其具备多线程处理能力.

(1)MutiThreadConnection类

 using System;
using System.Net.Sockets;
using System.Threading;
namespace MyHttpSever
{
    public class MutiThreadConnection : BaseConnection
    {
        public MutiThreadConnection(Socket sock):base(sock)
        {
        }
        public void run()
        {
            Console.WriteLine("当前线程ID是:" + Thread.CurrentThread.ManagedThreadId.ToString());
            try
            {
                string filename = getRequest();
                sendResponse(filename);
                Console.WriteLine("end one request.");
                Console.WriteLine("");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                ConClose();
            }
        }
    }
}

(2)Main方法

using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace MyHttpSever
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket ssock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);

            IPAddress hostIp = Dns.GetHostEntry("localhost").AddressList[0];
            IPEndPoint ep = new IPEndPoint(hostIp, 80);
            ssock.Bind(ep); //绑定

            Console.WriteLine("开始侦听.");
            //开始侦听
            ssock.Listen(32);
            while (true)
            {
                Socket sock = ssock.Accept(); //等待客户端请求
                MutiThreadConnection client = new MutiThreadConnection(sock);
                new Thread(new ThreadStart(client.run)).Start();
            }
        }
       
    }
}

(3)测试
a.启动服务器程序
在这里插入图片描述

b.打开两个浏览器窗口,分别输入:http:localhost/info.html(确保在你的C:\Inetpub\wwwroot目录下这样文件)
在这里插入图片描述
c.服务器输出如下:
在这里插入图片描述

d.当在第二个浏览器窗口输入地址时,服务器端输出如下:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是刘彦宏吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值