Tcp客户端不断开连接

时间:2013-12-23 07:20:54

标签: c# sockets networking asynchronous tcpclient

我的问题是我第一次使用应用程序异步将Tcp客户端连接到服务器 它连接和工作,但当我断开连接并再次连接时,数据发送两次就像 S8 S8

连接代码


                constatus.Text = "Connecting.....";
                //  newsock = null;
                newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //IPEndPoint iep = new IPEndPoint(IPAddress.Any, 20);
                IPEndPoint iep = new IPEndPoint(IPAddress.Parse(textBox2.Text), Convert.ToInt16(textBox3.Text));
                newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);        

数据发送代码


            if (!InvokeRequired)
            {
                try
                {
                    byte[] message = Encoding.ASCII.GetBytes(Allinput_Command);
                    client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), client);
                 }
                catch (Exception) { }                   
            }
            else
            {
                Invoke(new ThreadStart(data_send));
            }

断开代码


client.Close();
timer.Stop();
timer1.Stop();

请告诉我解决这个问题的正确途径.... 如果有人告诉我解决方案,我可以发送我的所有代码

1 个答案:

答案 0 :(得分:1)

在开始编写使用TCP的任何内容之前,请确保您具有在TCP之上分层的协议的规范。否则,无法修复此类错误。一旦有了规范,就很容易:

  1. 发送程序是否符合规范?如果没有,那就错了。

  2. 接收程序是否符合规范?如果没有,那就错了。

  3. 如果两个程序都遵循规范并且通信仍然不起作用,则规范将被破坏。

  4. 我敢打赌,你认为你正在发送消息,但实际上你正在发送字节。如果要发送消息,则需要一个说明消息开始和结束位置的规范,发送者和接收者都必须遵循该规范。