gpt4 book ai didi

c# - TCP 连接断开/或无法通过 TCP 接收数据

转载 作者:可可西里 更新时间:2023-11-01 02:42:45 25 4
gpt4 key购买 nike

我有一台客户端 PC 使用我编写的 TCP_client 程序通过 TCP 向我发送数据。基本上,我正在向服务器发送一条“Hello Message”。

class Program
{
const int ourPort = 9090;
static IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.10"), 3000);
static ASCIIEncoding encoder = new ASCIIEncoding();
static System.Timers.Timer aTimer;
static void Main(string[] args)
{
aTimer = new System.Timers.Timer(200);
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;

Console.Read();
}

private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
try
{
TcpClient client = new TcpClient();
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();

byte[] buffer = encoder.GetBytes("Hello Server!");

clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
catch (Exception ee)
{
Console.WriteLine(ee.ToString());
}
}

我正在使用我的 PC 使用我编写的 TCP_server 程序接收该数据。

class Server
{
private static TcpListener tcpListener;
static System.Timers.Timer aTimer;
static int count = 0;
public Server()
{
//
}

static void Main(string[] args)
{
tcpListener = new TcpListener(IPAddress.Any, 3000);
tcpListener.Start();

aTimer = new System.Timers.Timer(200);
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;


Console.Read();
}

private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
TcpClient client = tcpListener.AcceptTcpClient();
Thread.Sleep(2);
NetworkStream clientStream = client.GetStream();
Thread.Sleep(2);

byte[] message = new byte[4096];
int bytesRead;

bytesRead = 0;

try
{
bytesRead = clientStream.Read(message, 0, 4096);
client.Close();
}
catch (Exception ee)
{
Console.WriteLine("socket error");
Console.WriteLine(ee.ToString());
client.Close();
}

if (bytesRead == 0)
{
client.Close();
}
count++;

ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine(count + " " + encoder.GetString(message, 0, bytesRead));
}

总而言之,我遇到的问题是,我偶尔会在 TCP_server 程序的 Catch() 中遇到“套接字错误”。

错误:

System.IO.IOException: Unable to read data from the transport connection: An exi
sting connection was forcibly closed by the remote host. ---> System.Net.Sockets
.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size,
SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)
at test_tcp_manager.Server.OnTimedEvent(Object source, ElapsedEventArgs e) in
c:\Users\user\Documents\Visual Studio 2012\Projects\test_tcp_manager\test_tcp_ma
nager\Program.cs:line 52

错误不规律地出现一秒或几秒。我想知道为什么,我想知道如何解决这个问题。

U**来自用户输入的修复**来自用户 Usr 反馈的第一个代码修复:

tcp_client 代码现在看起来像这样:

 class Program
{
const int ourPort = 9090;
static IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("172.22.1.22"), 3000);
static ASCIIEncoding encoder = new ASCIIEncoding();
static void Main(string[] args)
{
while (true)
{
try
{
using( TcpClient client = new TcpClient())
{
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();

byte[] buffer = encoder.GetBytes("Hello Server!");

clientStream.Write(buffer, 0, buffer.Length);

client.Close();
}
}
catch (Exception ee)
{
Console.WriteLine(ee.ToString());
}
}
}
}

tcp_server 代码现在看起来像这样:

class Server
{
private static TcpListener tcpListener;
static int count = 0;
public Server()
{
//
}

static void Main(string[] args)
{
tcpListener = new TcpListener(IPAddress.Any, 3000);
tcpListener.Start();
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();

byte[] message = new byte[4096];
int bytesRead;

bytesRead = 0;

try
{
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ee)
{
Console.WriteLine("Socket rror");
Console.WriteLine(ee.ToString());
}
count++;

ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine(count + " " + encoder.GetString(message, 0, bytesRead));
}
}
}

最佳答案

  1. 不要忘记在发送消息后关闭客户端。连接将一直存在,直到 GC 决定将其关闭。
  2. 刷新网络流什么都不做。不要迷信并冲洗所有东西,因为它看起来更安全。
  3. 您正在接受计时器。我以前从未见过这种错误。你为什么要那样做?您应该在一个循环中接受所有连接的客户端,并独立地为它们提供服务。为什么每个计时器滴答将服务器限制为一个客户端?
  4. 去掉睡衣。每当您认为需要 sleep 时 - 多想想。
  5. 您假设您将在第一次阅读时阅读“消息”。 Read 至少返回一个字节。它不保证任何其他内容。 TCP 没有消息。确保您的代码可以按字节处理接收传入数据。
  6. 对所有一次性资源使用 using 语句,摆脱所有那些笨拙的 Close 调用。

很多问题。套接字编程很难。非常小心。

关于c# - TCP 连接断开/或无法通过 TCP 接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24765531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com