c# - 套接字使用。数据没有第二次发送
问题描述
问题描述。我发送和接收数据。当我启动程序时,我发送和接收的数据显示是正确的。如果在 1 分钟内重新启动程序,则显示的数据发送和接收是正确的。
但!如果我重新启动程序超过2分钟后,第一次接收和发送显示是正确的,但第二次发送和接收数据,不显示(((
发生了什么事,我如何解决这个问题???谢谢你的帮助!
public override bool Connect()
{
try
{
if (NetClient != null)
{
NetClient.Close();
}
NetClient = new Socket(ConnectionPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = NetClient.BeginConnect(ConnectionPoint, null, null);
bool success = result.AsyncWaitHandle.WaitOne(connectionDelay, false/*true*/);
if (NetClient.Connected)
{
Log("report.log", string.Format("Connection OK"));
return true;
}
Log("report.log", string.Format("NetClient is not connected"));
}
catch (Exception e)
{
MessageBox.Show(e.Message);
Log("report.log", string.Format("NetClient error while connecting: {0}", e.Message));
}
return false;
}
public override bool Send(byte[] data)
{
try
{
if (NetClient.Connected)
{
NetClient.SendTo(data, ConnectionPoint);
Thread.Sleep(transferDelay);
return true;
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return false;
}
public override string Receive(int length)
{
byte[] data = new byte[bufferSize]; // bufferSize = i tryed any buffer from 5 bytes to 16384 bytes
string strbuff = "";
try
{
if (NetClient.Connected)
{
do
{
IAsyncResult result = NetClient.BeginReceive(data, 0, bufferSize, SocketFlags.None, null, null);
bool success = result.AsyncWaitHandle.WaitOne(connectionDelay, true);
int receivedBytesCount = NetClient.EndReceive(result);
if (receivedBytesCount == 0)
{
receivedBytesCount = 0;
}
strbuff += Encoding.ASCII.GetString(data, 0, receivedBytesCount);
} while (NetClient.Available > 0);
if (NetClient != null && NetClient.Connected)
{
NetClient.Shutdown(SocketShutdown.Both);
NetClient.Close();
}
return strbuff;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public override void Disconnect()
{
try
{
if (NetClient.Connected)
{
NetClient.Shutdown(SocketShutdown.Both);
NetClient.Close();
}
else
{
if (NetClient != null)
{
NetClient.Close();
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
解决方案
推荐阅读
- r - 有没有办法根据分类列和日期列过滤 R 中的行
- excel - 如何在特定工作表中运行宏,但根据从另一个 Excel 文件/工作表维护的值控制开始?
- python - Python 条件拆分
- sql - 如何在 SQL 中的物化视图左侧添加序列?
- python - 如何使用方法链更改熊猫数据框中列的顺序?
- visual-studio-code - vscode 调试器中的变量名减少为一个字母,而不是完整的变量名
- node.js - AWS PUT 请求遇到“提供的关键元素与架构不匹配”。
- scala - 将 DATASet Api 与 Spark Scala 结合使用
- python - Python 不支持的操作数 int 和元组 - 尝试从 Excel 范围创建列表
- javascript - Node Mailer 不工作,即使它说它成功