耗尽最后60分 一定要得一结果 关于Socket的问题

v41dugu 2007-06-29 01:10:46
客户端和服务器都在本机
192.168.1.4是本机IP

服务器端:
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.4"),8888); //本地终结点
server.Bind(serverPoint); //绑定
server.Listen(100);

Socket s = server.Accept();
Console.WriteLine("s is Accept");

byte[] buffer = new byte[5];

int len = s.Receive(buffer);

Console.WriteLine("s第一次收到数据长度是:{0}", len);

len = s.Receive(buffer);
Console.WriteLine("s第二次收到数据长度是:{0}", len);


客户端:

Socket client = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(IPAddress.Parse("192.168.1.4"),8888);

Thread.Sleep(4000);

client.Shutdown(SocketShutdown.Both);
client2.Shutdown(SocketShutdown.Both);

client.Close();
client2.Close();


本来服务器的线程开始阻塞在s.Receive这里 因为客户端没有发送数据 但是当客户端的Thread.Sleep(4000)完了之后 调用了close函数 服务器的线程就开了
s可以无限的Receive数据了 而且每次的长度都是0
请高手来分析下是什么原因啊?
...全文
230 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wzd24 2007-06-29
  • 打赏
  • 举报
回复
LZ想干什么?上一贴已经告诉你了!还开贴来问??
RedGoldFish 2007-06-29
  • 打赏
  • 举报
回复
doushi(斗士) 说的不错,客户端已经把Socket连接关闭了,所以s.Receive(buffer)堵塞解除而且收到0字节
YUAN168 2007-06-29
  • 打赏
  • 举报
回复
不会,顶....
飞花丝雨 2007-06-29
  • 打赏
  • 举报
回复
s代表了与一个客户端的连接,Receive返回0表示对端已经关闭了,你还一直调用Receive,当然每次都返回0告诉你对端关闭了。
If you are using a connection-oriented Socket, the Receive method will read as much data as is available, up to the size of the buffer. If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧