c# 通过socket模拟HTTP协议,解析HTTP包头

找到很好的文章,可以应用到我正在开发的彩信MM7协议中
C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#

**//// <summary>
  
/// 接收数据的方法
  
/// </summary>
  
/// <param name="socket">Socket连接</param>
  
/// <param name="size">要接收的数据长度</param>
  
/// <returns>返回收到的字节数组</returns>
  public static byte[] ReceiveData(Socket socket,int size)
  
{
   
int total=0;     //收到的总的字节数
   int dataleft=size;    //剩余的字节数
   byte[] data=new byte[size];  //接收数据的数组
   int rece=0;      //收到的字节数
   
//循环接收数据
   while(total<size)
   
{
         rece
=socket.Receive(data,total,dataleft,SocketFlags.None);
      
//如果收到的字节数为0,那么说明连接断开,返回空的字节数组
      if(rece==0)
      
{
          
break;
         }

         total
+=rece;     //收到的字节数长度++
         dataleft-=rece;     //剩余的字节数--

      }

   
return data;      //返回
     }
c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#c#
方法重载

public static byte[] ReceiveData(Socket socket)
  
{
   
   
     StringBuilder header
=new StringBuilder();
   
string headertext="";
   
while(true)
   
{
    
byte[] data=new byte[1];
    
//接收一个字节
    int rece=socket.Receive(data,1,SocketFlags.None);
    
    
    
//转换为char
    char c=(char)data[0];
    
      header.Append(c);
    
//检查是否到了包头末尾,如果到了包头末尾,那么停止
    
//读取
    if(header.ToString().IndexOf("/r/n/r/n")>0)
    
{
     
string content="CONTENT-LENGTH:";
     
int start=header.ToString().ToUpper().IndexOf(content);
       headertext
=header.ToString().Substring(start+content.Length);
     
int end=headertext.IndexOf("/r/n");
       headertext
=headertext.Substring(0,end); //包体长度
     break;
      }

     }

   
//
   byte[] ds=ReceiveData(socket,Convert.ToInt16(headertext));
   
return ds;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值