如何调试为什么我的线程程序无法读取?

时间:2019-01-14 12:10:38

标签: c# multithreading tcp streaming

我必须使用线程并发发送和接收消息,但是我只能写数据而不能读。这是我的代码:

服务器端:

namespace ServerApplicaation
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener server = new TcpListener(IPAddress.Any,3300);
            server.Start();
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Send your data to {0}", client.Client.RemoteEndPoint);
            NetworkStream networkStream = client.GetStream();
            string str = "";
            int stream = 0;
            byte[] store;
            while (client.Connected)
            {
                Thread t1 = new Thread(() => Read(networkStream, out stream, out store));
                Thread t2 = new Thread(() => Write(networkStream, out str, out store));
                t1.Start();
                t2.Start();
            }
        }

        private static void Read(NetworkStream networkStream, out int stream, out byte[] store)
        {
            store = new byte[1024];
            stream = networkStream.Read(store, 0, store.Length);
            string s = Encoding.ASCII.GetString(store, 0, stream);
            Console.WriteLine("Client: {0}", s);
        }

        private static void Write(NetworkStream networkStream, out string str, out byte[] store)
        {
            str = Console.ReadLine();
            store = Encoding.ASCII.GetBytes(str);
            networkStream.Write(store, 0, store.Length);
        }
    }
}

客户端:

namespace ClientApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            TcpClient client = new TcpClient("127.0.0.1",3300);
            NetworkStream networkStream = client.GetStream();
            byte[] store;
            string str = "";
            int stream = 0;
            while (client.Connected)
            {
                //Read(networkStream, stream, store);
                Thread t1 = new Thread(() => Write(networkStream, out str, out store));
                Thread t2 = new Thread(() => Read(networkStream, out stream, out store));
                t1.Start();
                t2.Start();


            }

        }

        private static void Read(NetworkStream networkStream, out int stream, out byte[] store)
        {
            store = new byte[1024];
            stream = networkStream.Read(store, 0, store.Length);
            string s = Encoding.ASCII.GetString(store, 0, stream);
            Console.WriteLine("Server: {0}", s);
        }

        private static void Write(NetworkStream networkStream, out string str, out byte[] store)
        {
            //SENDING THE MESSAGE
            str = Console.ReadLine();
            store = Encoding.ASCII.GetBytes(str);
            networkStream.Write(store, 0, store.Length);
        }
    }
}

我想进行并发通信。

0 个答案:

没有答案