c#如果语句总是返回false

时间:2012-10-14 17:37:56

标签: c# linux if-statement mono

我目前正在为个人项目开发一个小型服务器/客户端应用程序。当客户端从Windows PC运行时,服务器应在Mono下以Linux运行。

我遇到的问题是我将数据传递给服务器(在这种情况下,字符串值为“on”和“off”)但是if语句总是返回false值。

服务器的代码如下

public void startServer() {
    TcpListener listen = new TcpListener(serverIP, 10000);
    listen.Start();

    Console.Clear();
    Console.WriteLine("IP Address = {0}", serverIP.ToString());
    Console.WriteLine("Server is listening for connection");

    Socket a = listen.AcceptSocket();

    Console.WriteLine("Connection from {0}", a.RemoteEndPoint);

    ASCIIEncoding respond = new ASCIIEncoding();
    a.Send(respond.GetBytes("You are connected to LED Control Server"));

    bool keepListening = true;

    while (keepListening) {
        byte[] b = new byte[1000];
        a.Receive(b);
        Console.WriteLine("Message Received from {0}, string: {1}", a.RemoteEndPoint, recData(b));
        string serverMsg = procIns(recData(b));
        a.Send(respond.GetBytes(serverMsg));
    }
}

private string recData(byte[] b) //receiving data from the client {
    int count = b.Length;
    string message = "";
    for (int a = 0; a < count; a++) {
        message += Convert.ToChar(b[a]);
    }
    return message;
}

private string procIns(string instruction) {
    string returnMsg;

    Console.WriteLine(instruction.ToLower());

    if (instruction.ToLower() == "on") {
        FileGPIO gpio = new FileGPIO();
        gpio.OutputPin(FileGPIO.enumPIN.gpio17, true);
        returnMsg = "GPIO 17 1";
    } else if (instruction.ToLower() == "off") {
        FileGPIO gpio = new FileGPIO();
        gpio.OutputPin(FileGPIO.enumPIN.gpio17, false);
        returnMsg = "GPIO 17 0";
    } else {
        returnMsg = "Invalid Command";
    }

    return returnMsg;
}

procIns方法中if语句返回false的原因是逃避我,如果有人可以提供任何建议我会很感激!

2 个答案:

答案 0 :(得分:1)

我猜它必须是填充空格。试试这个......

if (instruction.Trim().ToLower() == "on")

答案 1 :(得分:0)

   while (keepListening) {
            byte[] b = new byte[1000];
            int bytesRcvd = a.Receive(b);
            Console.WriteLine("Message Received from {0}, string: {1}", a.RemoteEndPoint, recData(b));
            string serverMsg = procIns(recData(b, bytesRcvd ));
            a.Send(respond.GetBytes(serverMsg));
        }

a.Receive(b)方法返回接收的字节数。您可以将值存储在某个变量中,并将变量传递给recData方法。

    private string recData(byte[] b, int bytesRcvd) {
    string message = "";
    for (int a = 0; a < bytesRcvd; a++) {
        message += Convert.ToChar(b[a]);
    }
    return message;
}

接收的字节数有助于截断字节数组中的额外值。