会员
众包
新闻
博问
闪存
赞助商
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
会员中心
简洁模式
...
退出登录
注册
登录
Pierce
Goodbye's the saddest word I'll ever hear, Goodbye's the last time I will hold you near, Someday you'll say that word and I will cry, It'll break my heart to hear you say Goodbye, Till we meet again until then goodbye
Socket模拟Http协议,读取http header,根据content-length的值,读取Http body
接收数据方法:
/**/
///
<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;
//
返回
}
接收数据方法重载:
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;
}
posted on
2005-06-27 12:17
Pierce
阅读(
11881
) 评论(
14
)
收藏
举报
刷新页面
返回顶部
导航
博客园
首页
新随笔
联系
订阅
管理