为什么socket.Available老是为0

shizhusz110 2008-10-30 02:34:59

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
Connect();
}
private void Connect()
{
//CloseConnection();


socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,ProtocolType.Tcp);
socket.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.SendTimeout, 5000);
IPAddress ipAdd=IPAddress.Parse("127.0.0.1");
int port = System.Convert.ToInt32("23");
IPEndPoint hostEndPoint = new IPEndPoint(ipAdd, port);

try
{
socket.Connect(hostEndPoint);
if (socket.Connected)
{
Receive();
}

}
catch (Exception e)
{
this.Response.Write("<script>alert('连接失败')</script>");
return;
}
}
private void Receive()
{
//用于接收数据的缓冲
byte[] buf;
string result="";

int count = socket.Available;

if (count > 0)
{
buf = new byte[count];
socket.Receive(buf);
result = ProcessOptions(buf);
if (result!="")
{
result=result.Replace("\r","\n");
this.TextBox1.Text+=result.Replace("\r\n","\n");
}

RespondToOptions();
}

}

为什么int count = socket.Available;老是为0???!!谢谢回复!!
...全文
1067 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
shizhusz110 2008-10-30
  • 打赏
  • 举报
回复
谢谢你,我该成这样了:

private void Receive()
{
//用于接收数据的缓冲
byte[] buf;
string result="";

buf = new byte[max_char];
socket.Receive(buf);
result = ProcessOptions(buf);
if (result!="")
{
result=result.Replace("\r","\n");
this.TextBox1.Text+=result.Replace("\r\n","\n");
}

RespondToOptions();
}

我最后去掉了判断数据是接受到了,老超时:Welcome to Microsoft Telnet Service login: Session timed out.Telnet Server has closed the connection
greystar 2008-10-30
  • 打赏
  • 举报
回复
// FIONREAD is also available as the "Available" property.
public const int FIONREAD = 0x4004667F;

static void DisplayPendingByteCount(Socket s)
{
byte[] outValue = BitConverter.GetBytes(0);

// Check how many bytes have been received.
s.IOControl(FIONREAD, null, outValue);

uint bytesAvailable = BitConverter.ToUInt32(outValue, 0);
Console.WriteLine("server has {0} bytes pending. Available property says {1}.",
bytesAvailable, s.Available);

return;
}
greystar 2008-10-30
  • 打赏
  • 举报
回复
如果当前使用的是非阻止 Socket,一种较好的做法是在调用 Receive 之前使用 Available 来确定数据是否排队等待读取。可用的数据即网络缓冲区中排队等待读取的全部数据。如果在网络缓冲区中没有排队的数据,则 Available 返回 0。

greystar 2008-10-30
  • 打赏
  • 举报
回复
对方有发送数据吗.
你这个不用判断,你是用同步的方式.

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

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