Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

.net - C# TcpListener Crashes after certain amount of time

Apparently, after like 15s the client crashes then the server closes with error "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."

I tried multiple things to try to somewhat fix it there comes the code:

Server:

private static readonly object _lock = new object();
    private static readonly Dictionary<int, TcpClient> list_clients = new Dictionary<int, TcpClient>();

    public static void Main(string[] args)
    {
        Console.Title = "Server";
        int count = 1;

        TcpListener socket = new TcpListener(IPAddress.Any, 5000);
        socket.Start();
        
            while (true)
            {

                TcpClient client = socket.AcceptTcpClient();
                lock (_lock) list_clients.Add(count, client);
                Console.WriteLine("Someone has been connected!");

                Thread thread = new Thread(handle_clients);
                thread.Priority = ThreadPriority.Lowest;
                thread.Start(count);
                count++;
            }
        }

    public static void handle_clients(object obj)
    {
        int id = (int) obj;
        TcpClient client;

        lock (_lock) client = list_clients[id];

      
            while (true)
            {
            
                Stream stream = client.GetStream();
                byte[] buffer = new byte[1024];
       
            int byte_counter = stream.Read(buffer, 0, buffer.Length);

            if (byte_counter != 0)
                {
                string data = Encoding.ASCII.GetString(buffer, 0, byte_counter);
                SendData(data);
                Console.WriteLine(data);

            }

               
            
            }

        lock (_lock) list_clients.Remove(id);
        client.Client.Shutdown(SocketShutdown.Both);
        client.Close();
        
    }

    public static void SendData(string data)
    {
        byte[] buffer = Encoding.ASCII.GetBytes(data + "
");
        lock (_lock)
        {
            foreach (TcpClient tcpClient in list_clients.Values)
            {
                Stream stream = tcpClient.GetStream();
                stream.Write(buffer, 0, buffer.Length);
            }
        }
    }

And there's the Client:

 public void GetData()
    {
        try
        {
           
            byte[] receivedBytes = new byte[1024];
            int byte_counter = stream.Read(receivedBytes,0,receivedBytes.Length);
            if (byte_counter > 0)
            {
                string s = Encoding.ASCII.GetString(receivedBytes, 0, byte_counter);
                if (!string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s))
                {
                    usersTextBox1.Content = s.ToString();
                   
                }
            }
        } catch { }
    }

     public MainWindow()
    {
        InitializeComponent();
        DispatcherTimer dispatcherTimer =
            new DispatcherTimer();
        dispatcherTimer.Interval = new TimeSpan(0,0,15);
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Start();
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        int port = 5000;
        client.Connect(ip, port);
        stream = client.GetStream();
    }

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        if (client.Connected)
        {
            GetData();
        }
    }

basically whenever I run the server after that I run 2 clients and type something then send after certain amount of time the message will be shown in the label. But if i stop doing that sort of activity like about 15 seconds the client completely freezes and becomes not responding application then I have to close it and will also crash the server cause of disconnecting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...