简体   繁体   中英

System.ObjectDisposedException in TCP sockets in C#

Here is my server:

class Server
    {
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 5004);
            listener.Start();
            TcpClient client;
            while (true)
            {
                client = listener.AcceptTcpClient();
                if (client.Connected)
                {
                    Console.WriteLine("client connected");
                    break;
                }

            }


            NetworkStream sr = client.GetStream();
            while (true)
            {
                byte[] message = new byte[1024];
                sr.Read(message, 0, message.Length);
                sr.Close();
                Console.WriteLine(message.ToString());
            }

        }
    }

and here is my client:

class Program
    {

        static void Main(string[] args)
        {
            TcpClient client = new TcpClient();
            Console.WriteLine("Insert server address");
            string server = Console.ReadLine();
            if (server == "")
            {
                server = "192.168.1.2";
            }
            client.Connect(IPAddress.Parse(server), 5004);

            NetworkStream sw = client.GetStream();
            while (true)
            {
                byte[] message = Encoding.ASCII.GetBytes(Console.ReadLine());
                sw.Write(message, 0, message.Length);
                sw.Close();
            }

        }

    }

When I run my server and the client first everything works and a "client connected" message appears. The problem is when I am trying to send a message from client to the server, a System.ObjectDisposedException is raised at the server in the sr.Read(message, 0, message.Length); line. Any idea how can I solved it or what is the cause?

You are closing the stream in the while loop, for both client and server. Move the Close below outside of the loop, or better still, make use of fact that Close calls Dispose , which allows you to use the IDisposable interface features like using :

using (NetworkStream sw = client.GetStream())
{
     while (true)
     {
         byte[] message = Encoding.ASCII.GetBytes(Console.ReadLine());
         sw.Write(message, 0, message.Length);
         // Todo : Implement some kind of termination to the loop
     }
     sw.Flush();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM