TcpClient tcpClient = new TcpClient();
tcpClient.Connect(IPAddress.Parse(textBox1.Text), Int32.Parse(textBox2.Text));NetworkStream ns = tcpClient.GetStream();
Byte[] sendBytes = Encoding.UTF8.GetBytes(textBox3.Text);
ns.Write(sendBytes, 0, sendBytes.Length);
richTextBox1.AppendText(DateTime.Now.ToString() + "-发送成功");
ns.Close();
tcpClient.Close();这是我TCP客户端的主要代码,不明白的是,如果每次都tcpClient.Close();的话,那么每发送一次数据岂不是都一创建一个连接,发送完了再断开吗?

解决方案 »

  1.   

    你可以将tcpClient 申明为全局变量,再循环操作中该收的收了,该发的发了,退出程序或者点击指定的“断开”按钮,再执行Close()即可。
      

  2.   

    我现在尝试这样做了,但是有一个新的问题,就是我的服务端,只有在客户端断开时,才会把接收到的内容显示出来,难道是我服务端写的有问题?
    主要代码如下:        private void frmMain_Load(object sender, EventArgs e)
            {
                Thread thread = new Thread(Listen);
                thread.Start();
                WriteLog("线程启动成功!");
            }
            Dictionary<string, TcpClient> socketList = new Dictionary<string, TcpClient>();
            private void Listen()
            {
                IPAddress ipAddress = IPAddress.Any;            TcpListener tcpListener = new TcpListener(ipAddress, 8899);
                tcpListener.Start();            while (true)
                {
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();                socketList.Add(DateTime.Now.ToString(), tcpClient);                Thread thread = new Thread(checkMess);
                    thread.Start(tcpClient);            }
            }        private void checkMess(object obj)
            {
                TcpClient tcpClient = obj as TcpClient;
                if (tcpClient.Connected)
                {
                    NetworkStream ns = tcpClient.GetStream();
                    StreamReader sr = new StreamReader(ns);
                    string result = sr.ReadToEnd();
                    WriteLog(result);
                }
            }
      

  3.   

    最后显示是因为你使用了sr.ReadToEnd(),当你连接还存在的时候,是没有"End"的。
    你可以换用sr.ReadLine()看看。
      

  4.   

    用ReadLine也不行,还是得客户端断开时才一起显示!