TcpClient不发送消息
本文关键字:消息 TcpClient | 更新日期: 2023-09-27 18:15:16
我用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(
}
不幸的是,几秒钟后,我在我的服务器上(用c++编写)得到了"由于线程退出或应用程序请求,i/o操作已被中止"。但是,如果我更改此代码,并将sendfirstpacket()放入while循环中,它将发送数据包正确(i计数超过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(
}
这是什么原因呢?
听起来你在服务器端有问题。例如,您可能试图读取比发送更多的字节,如果您快速发送许多消息,这似乎是"固定的"。