本文介绍了TcpClient.connect给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,以与服务器之间收发一些数据.我需要在发送一些数据之前进行连接,并且需要保持打开状态,以便用户可以连续发送数据.用户可以通过单击断开按钮随时关闭连接.我创建了2个按钮,一个用于连接,另一个用于断开连接.断开按钮后面的代码如下:-

I am writing an application to send/receive some data to and from a server. I need to make a connection before sending some data and need to keep it open so that user can send data continuously. The user can close the connection at any time by clicking on disconnect button. I created 2 buttons, one to connect and one to disconnect. Code behind Disconnect button is as below:-

private void button1_Click(object sender, EventArgs e)
    {
        if (tcpclnt.Connected)
        {
            tcpclnt.Client.Disconnect(false);
            stm.Close();
        }
        else
        {
            MessageBox.Show("Not Connected");
        }
    }




连接按钮后面的代码如下:-




code behind connect button is as below:-

public ASCIIEncoding asen = new ASCIIEncoding();
public TcpClient tcpclnt = new TcpClient();
public NetworkStream stm;

private void Connect_Click(object sender, EventArgs e)
{
    if (!tcpclnt.Connected)
    {
        tcpclnt.Connect("XX.XX.XX.XX", 5500);
        MessageBox.Show("Connected to server");


        stm = tcpclnt.GetStream();

        string sysname = "000B0000" + SystemName.Text.ToString();
        byte[] sys1 = asen.GetBytes(sysname);
        sys1[0] = 0; sys1[1] = 0;
        sys1[2] = 0; sys1[3] = 0xB;
        sys1[4] = 0; sys1[5] = 0;
        sys1[6] = 0; sys1[7] = 0;
        try
        {
            stm.Write(sys1, 0, sys1.Length);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            MessageBox.Show("Error in Sending data");
        }
        if (stm.DataAvailable)
        {
            try
            {
                byte[] bb = new byte[600];
                int k = 8;
                k = stm.Read(bb, 0, bb.Length);
                string value = ASCIIEncoding.ASCII.GetString(bb, 8, k - 8);
                MessageBox.Show(value.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                MessageBox.Show("Error in Reading data");
            }
        }
     }
     else {
            MessageBox.Show("Already Connected");
    }
}




现在,当我单击连接"按钮时,它已连接到服务器并且工作正常.现在,当我单击断开连接"按钮并再次单击连接"按钮以建立连接时,它会在tcpclient.connect行上引发异常.我不明白为什么或如何解决该问题,请提出建议.

Thnx,
A




Now, when I click on connect button it connects to server and works fine. Now when I clieck on Disconnect button and again click on connect button to make the connection, it''s throwing an exception on tcpclient.connect line. I don''t understand why or how can I solve it, Please suggest.

Thnx,
A

推荐答案


这篇关于TcpClient.connect给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 20:39