TCP连接断开或无法通过TCP接收数据

本文关键字:TCP 数据 连接 断开 | 更新日期: 2023-09-27 18:13:09

我有一台客户端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));
        }
    }
}

TCP连接断开或无法通过TCP接收数据

    发送消息后不要忘记关闭客户端。该连接将保持延迟,直到GC决定关闭它。
  1. 刷新一个网络流不做任何事情。不要迷信,把所有东西都冲干净,因为这样看起来更安全。
  2. 你正在接受一个计时器。我以前从未见过这种错误。你为什么要这么做?您应该在一个循环中接受所有连接的客户机,并独立地为它们提供服务。为什么要将服务器限制为每个计时器一个客户端?
  3. 取消睡眠。当你觉得你需要睡觉的时候——再努力想想。
  4. 您假设您将在第一次读取时读取"消息"。Read返回至少一个字节。它不能保证其他任何东西。TCP没有消息。确保你的代码可以按字节处理接收传入数据。
  5. 对所有的一次性资源使用using语句,避免那些尴尬的Close calls。

许多问题。套接字编程很难。