无法从TCP服务器读取数据

时间:2019-10-10 06:02:41

标签: c# tcp tcpclient

我创建了一个简单的C#客户端应用程序。一旦连接到服务器,它应该读取从服务器发送的消息。它还具有将消息发送到服务器的功能。但是我无法弄清楚读取数据的正确方法。

一旦连接到服务器,我就生成一个线程。线程以无限循环运行,并且具有两个分别用于读取和写入的接口。从ButtonClick事件中调用Connect()方法。

我的代码段如下:


namespace WpfApp1
{

    public class TCPClientClass
    {
        private StreamWriter SwSender;
        NetworkStream Sender;
        NetworkStream Receiver;
        //private StreamReader SrReciever;
        private Thread thrMessaging;
        TcpClient tcp;
        bool connected = false;

        public bool Connected { get { return connected; } set { connected = value; } }
        //public bool Connect(IPAddress IP, int nPortNo)
        public async Task Connect(IPAddress IP, int nPortNo)
        {
            tcp = new TcpClient();
            try
            {
                //tcp.Connect(strIPAddress.Parse("192.168.137.1"), 2000);
                // tcp.Connect(IP , nPortNo);
                await tcp.ConnectAsync(IP, nPortNo);
                thrMessaging = new Thread(new ThreadStart(ThreadFunction));
                thrMessaging.Start();
                Connected = true;
            }
            catch
            {
                MessageBox.Show("Unable to connect to server");
                //return false;
            }
            //return true;
        }

        public void Disconnect()
        {
            Sender?.Close();
            Receiver?.Close();
            tcp?.Close();
            //tcp?.Client.Disconnect(false);
            thrMessaging.Abort();
            Connected = false;
        }
        private void ThreadFunction()
        {
            while (thrMessaging.IsAlive)
                DoTasks();
        }
        private void DoTasks()
        {
            if (Connected)
            {
                var a = ReadMessages();
                SendMessages();
            }
        }

        private /*void*/async Task ReadMessages()
        {
            byte[] data = new byte[4096];
            //Int32 bytesRead = 0;
            //Task<int> bytesReadTask;
            String responseData = String.Empty;
            Receiver = tcp.GetStream();

            try
            {
                //bytesReadTask = Receiver.ReadAsync(data, 0, data.Length);

                //responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytesReadTask.Result);
                var response = await Receiver.ReadAsync(data, 0, data.Length);
                MessageBox.Show("Server response was " + response);
                Thread.Sleep(1000);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void SendMessages()
        {
            try
            {
                string strSendData = "Hello from GUI";
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(strSendData);
                Sender = tcp.GetStream();

                Sender.Write(data, 0, data.Length);
                Sender.Flush();
                Thread.Sleep(1000);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您应该更改

class Testing(unittest.TestCase):
    @StdoutUnittestMixin.monkey_patch_stdout
    def test_wrong_input_outputs_false_with_short_str(self):
        self.assertTrue(foo("123"))

    var response = await Receiver.ReadAsync(data, 0, data.Length);
    MessageBox.Show("Server response was " + response);

如果仍然有问题..我的服务器代码:

    var response = await Receiver.ReadAsync(data, 0, data.Length);
    string result = System.Text.Encoding.Default.GetString(data);
    MessageBox.Show("Server response was " + result);