我在使用C#TcpClient发送数据时遇到问题。
这就是我的代码的样子:
public Connection()
{
try
{
client = new TcpClient("127.0.0.1", 7171);
writer = new StreamWriter(client.GetStream());
client.Client.NoDelay = true;
client.NoDelay = true;
sendFirstPacket();
while (true)
{
if (client.GetStream().DataAvailable)
Logger.log(Log_Type.ERROR, "mam cos");
}
Logger.log(Log_Type.INFO, "Spoko luz");
}
catch (Exception ex)
{
Logger.log(Log_Type.ERROR, ex.Message);
}
finally
{
//client.Close();
}
}
void onSendDone()
{
}
void sendFirstPacket()
{
writer.Write((byte)10);
writer.Write((ushort)2);
writer.Write((ushort)854);
UInt32[] k = new UInt32[4];
k[0] = (12444 << 16) | 12444;
k[1] = (12444 << 16) | 12444;
k[2] = (12444 << 16) | 12444;
k[3] = (12444 << 16) | 12444;
writer.Write((byte)0); // first byte have to be 0
writer.Write((UInt32)k[0]);
writer.Write((UInt32)k[1]);
writer.Write((UInt32)k[2]);
writer.Write((UInt32)k[3]);
writer.Flush();
//client.GetStream().Write(
}
不幸的是,几秒钟之后我的服务器上用“线程退出或应用程序请求”中断了“i / o操作已中止”(用C ++编写)。 但是,如果我更改此代码,并将sendFirstPakcet()放入while循环,它将发送数据包正确(我计数超过700个循环),然后异常抛出:无法将数据写入传输连接:现有连接被强制关闭远程主机。
public Connection()
{
try
{
client = new TcpClient("127.0.0.1", 7171);
writer = new StreamWriter(client.GetStream());
client.Client.NoDelay = true;
client.NoDelay = true;
sendFirstPacket();
while (true)
{
if (client.GetStream().DataAvailable)
Logger.log(Log_Type.ERROR, "mam cos");
sendFirstPacket();
}
Logger.log(Log_Type.INFO, "Spoko luz");
}
catch (Exception ex)
{
Logger.log(Log_Type.ERROR, ex.Message);
}
finally
{
//client.Close();
}
}
void onSendDone()
{
}
void sendFirstPacket()
{
writer.Write((byte)10);
writer.Write((ushort)2);
writer.Write((ushort)854);
UInt32[] k = new UInt32[4];
k[0] = (12444 << 16) | 12444;
k[1] = (12444 << 16) | 12444;
k[2] = (12444 << 16) | 12444;
k[3] = (12444 << 16) | 12444;
writer.Write((byte)0); // first byte have to be 0
writer.Write((UInt32)k[0]);
writer.Write((UInt32)k[1]);
writer.Write((UInt32)k[2]);
writer.Write((UInt32)k[3]);
writer.Flush();
//client.GetStream().Write(
}
这可能是什么原因?
答案 0 :(得分:0)
听起来你在服务器端有问题。例如,您可能正在尝试读取比发送的字节数更多的字节,这似乎是&#34;固定的&#34;如果您快速发送许多消息。