C#如果语句没有执行

时间:2017-03-10 05:22:24

标签: c# network-programming tcpclient tcplistener

我正在玩C#中的网络,基本上我想做的是当客户端发送消息" shutdown"到服务器,它将启动完全关闭。但是,在服务器方面我的"如果"声明永远不会被执行,我不知道为什么;帮助将不胜感激(我在C#lol没有那么先进)

服务器端:

Console.Title = "RemoteControl Server v1.0";
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        TcpListener listener = new TcpListener(ip, 8080);
        Console.WriteLine("Server started!");
        Console.WriteLine("Listening for client connection on port 8080..");

        Console.Clear();

        listener.Start();
        TcpClient client = listener.AcceptTcpClient();
        Console.WriteLine("Client connected from: " + client.Client.RemoteEndPoint);
        NetworkStream stream = client.GetStream();

        while (true)
        {
            byte[] buffer = new byte[client.ReceiveBufferSize];
            int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);

            string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);

            // THIS BIT DOESN'T GET EXECUTED

            if (data == "shutdown")
            {
                Console.WriteLine("Shutdown command acknowledged.");
                // do stuff..
            }
            Console.WriteLine(data);
        }

客户端

        Console.Title = "RemoteControl Client v1.0";

        Console.WriteLine("Connecting to server..");
        try
        {
            TcpClient client = new TcpClient("127.0.0.1", 8080);
            NetworkStream stream = client.GetStream();
            Console.WriteLine("Connected!");

            while (true)
            {
                Console.Write("> ");
                byte[] msg = ASCIIEncoding.ASCII.GetBytes("> " + Console.ReadLine());
                stream.Write(msg, 0, msg.Length);
            }
        }
        catch (Exception ex)
        {
            Console.Clear();
            Console.WriteLine("Couldn't connect to server! Stacktrace:");
            Console.WriteLine(ex.StackTrace);
            Console.WriteLine();
            Console.WriteLine("Press any key to continue..");
            Console.ReadKey();
        }

1 个答案:

答案 0 :(得分:0)

发现问题..看起来我正在发送">"通过客户端的消息中的符号,我只是检查传入的文本是否是"关闭"。