如何使用相同的Button单独执行代码

时间:2017-04-27 17:29:42

标签: c# button

private void btnSend_Click(object sender, EventArgs e)
{
    IPAddress IP = IPAddress.Parse("127.0.0.1");
    TcpClient Client = new TcpClient();
    Client.Connect(IP, 5550);
    Stream MessageStream = Client.GetStream();
    ASCIIEncoding encoder = new ASCIIEncoding();

    void SendServerMessage(string Message)
    {
        byte[] encodedMessage = encoder.GetBytes(Message);

        MessageStream.Write(encodedMessage, 0, encodedMessage.Length);
        MessageStream.Flush();

        Client.Close();
    }

    SendServerMessage(textBox2.Text);   
}

我希望当我第一次执行所有操作时单击按钮,以及第二次单击按钮时,只执行SendServerMessage()。

2 个答案:

答案 0 :(得分:0)

如果您将TcpClient作为类属性,那么您可以检查它是否为null,然后根据需要创建它。

我重新组织了您的代码,以分离出您正在进行的每个不同的功能。以下是Modular programming的wiki文章。这是一个很好的做法,可以使您的代码更清晰,更易于维护。

private TcpClient client { get; set; }
private string ipAddressString = "127.0.0.1";
private int port = 5550;

private void btnSend_Click(object sender, EventArgs e)
{
    IPAddress ipAddress = IPAddress.Parse(ipAddressString);
    TcpClient client = getConnection(ipAddress);

    sendServerMessage(client, textBox2.Text);
}

private TcpClient getConnection(IPAddress ipAddress)
{
    if (client == null)
        client = new TcpClient();
    if (!client.Connected)
        client.Connect(ipAddress, port);
    return client;
}

private void sendServerMessage(TcpClient client, string message)
{
    Stream messageStream = client.GetStream();
    ASCIIEncoding encoder = new ASCIIEncoding();
    byte[] encodedMessage = encoder.GetBytes(message);

    messageStream.Write(encodedMessage, 0, encodedMessage.Length);
    messageStream.Flush();
}

答案 1 :(得分:0)

感谢Blake Thingstad。这是我使用的代码:

private TcpClient client { get; set; }
    private string ipAddressString = "127.0.0.1";
    private int port = 5550;

    private void btnSend_Click(object sender, EventArgs e)
    {
        IPAddress ipAddress = IPAddress.Parse(ipAddressString); 
        if (client == null)
        {
            TcpClient client = connect(ipAddress);
        }
        sendServerMessage(client, textBox2.Text);
    }

    private TcpClient connect(IPAddress ipAddress)
    { 
        client = new TcpClient();
        client.Connect(ipAddress, port);
        return client;
    }

    private void sendServerMessage(TcpClient client, string message)
    {
        Stream messageStream = client.GetStream();
        ASCIIEncoding encoder = new ASCIIEncoding();
        byte[] encodedMessage = encoder.GetBytes(message);

        messageStream.Write(encodedMessage, 0, encodedMessage.Length);
        messageStream.Flush();
    }

区别在于我在btnSend_Click中询问了client = null