1

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

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

来自服务器的代码如下

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 的原因使我无法理解,如果有人可以提供任何建议,我将不胜感激!

4

2 回答 2

1

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

if (instruction.Trim().ToLower() == "on")
于 2012-10-14T17:48:23.880 回答
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;
}

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

于 2012-10-14T18:11:30.667 回答