当我从客户端向服务器发送命令时,仅当请求发送两次时,客户端才会收到响应

时间:2017-05-04 17:34:20

标签: c# sockets tcp server client

我正在尝试向服务器发送命令,例如请求服务器发回其目录中的文件列表。问题是,当我将“list”命令发送到服务器时,我必须发送两次,以便服务器将文件列表发送回客户端。我确信服务器在服务器端同时接收命令我打印应该在控制台上发送给客户端的结果,并且它出现两次。

我使用C#和TCPListeners来监听传入的响应或命令,并使用TCPClient在服务器和客户端之间发送响应或命令。

客户端代码

    private TcpListener tcpListener = new TcpListener(9090);
    private void button3_Click(object sender, EventArgs e)
    {
        Byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("list");
        try
        {
            TcpClient clientSocket = new TcpClient(serverIPFinal, 8080);
            if (clientSocket.Connected)
            {
                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Write(bytesToSend, 0, bytesToSend.Length);
               // networkStream.Close();
               // clientSocket.Close();
                thdListener = new Thread(new ThreadStart(listenerThreadList));
                thdListener.Start();
            }
        }
        catch
        {
            isConnectedLbl.Text = "Server not running";
        }
    }
    //Listener Thread to receive list of files.
    public void listenerThreadList()
    {

        tcpListener.Start();

        while (true)
        {
            handlerSocket = tcpListener.AcceptSocket();
            if (handlerSocket.Connected)
            {
                Control.CheckForIllegalCrossThreadCalls = false;
                lock (this)
                {
                    if (handlerSocket != null)
                    {
                        nSockets.Add(handlerSocket);
                    }
                }
                ThreadStart thdstHandler = new
                ThreadStart(handlerThreadList);
                Thread thdHandler = new Thread(thdstHandler);
                thdHandler.Start();
            }
        }
    }
    //Handler Thread to receive list of files.
    public void handlerThreadList()
    {

        Socket handlerSocketList = (Socket)nSockets[nSockets.Count - 1];
        NetworkStream networkStreams = new NetworkStream(handlerSocketList);

        int requestRead = 0;
        string dataReceived;
        byte[] buffer = new byte[1024];
        //int iRx = soc.Receive(buffer);
        requestRead = networkStreams.Read(buffer, 0, 1024);
        char[] chars = new char[requestRead];

        System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
        int charLen = d.GetChars(buffer, 0, requestRead, chars, 0);
        dataReceived = new System.String(chars);

        Console.WriteLine(dataReceived);
        MessageBox.Show(dataReceived);

        //tcpListener.Stop();
        thdListener.Abort();


    }

服务器代码:

    TcpListener tcpListener = new TcpListener(8080);        
    public void listenerThreadCommands()
    {

        tcpListener.Start();
        while (true)
        {
            handlerSocket = tcpListener.AcceptSocket();

            if (handlerSocket.Connected)
            {
                Control.CheckForIllegalCrossThreadCalls = false;
                connections.Items.Add(
                handlerSocket.RemoteEndPoint.ToString() + " connected.");
                // clientIP = handlerSocket.RemoteEndPoint.ToString();
                lock (this)
                {
                    nSockets.Add(handlerSocket);
                }
                ThreadStart thdstHandler = new
                ThreadStart(handlerThreadCommands);
                Thread thdHandler = new Thread(thdstHandler);
                thdHandler.Start();
                //tcpListener.Stop();


                //handlerSocket.Close();
            }
        }

    }
    //Handler Thread to receive commands
    public void handlerThreadCommands()
    {
        Socket handlerSocketCommands = (Socket)nSockets[nSockets.Count - 1];

        NetworkStream networkStream = new NetworkStream(handlerSocketCommands);

        int requestRead = 0;
        string dataReceived;
        byte[] buffer = new byte[1024];
        requestRead = networkStream.Read(buffer, 0, 1024);
        char[] chars = new char[requestRead];

        System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
        int charLen = d.GetChars(buffer, 0, requestRead, chars, 0);
        dataReceived = new System.String(chars);

        //connections.Items.Add(dataReceived);
        if (dataReceived.Equals("list"))
        {
            localDate = DateTime.Now;

            Files = Directory.GetFiles(System.IO.Directory.GetCurrentDirectory())
                                 .Select(Path.GetFileName)
                                 .ToArray();
            String FilesString = "";
            for (int i = 0; i < Files.Length; i++)
            {
                FilesString += Files[i] + "\n";
            }
            String clientIP = handlerSocketCommands.RemoteEndPoint.ToString();
            int index = clientIP.IndexOf(":");
            clientIP = clientIP.Substring(0, index);
            WriteLogFile(logFilePath, clientIP, localDate.ToString(), " ", "list");
            Console.WriteLine(clientIP);
            Console.WriteLine(FilesString);

            Byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(FilesString);

            try
            {
                WriteLogFile(logFilePath, clientIP, localDate.ToString(), " ", "list-response");

                TcpClient clientSocket = new TcpClient(clientIP, 9090);
                if (clientSocket.Connected)
                {

                    NetworkStream networkStreamS = clientSocket.GetStream();
                    networkStreamS.Write(bytesToSend, 0, bytesToSend.Length);
                    networkStreamS.Close();
                    clientSocket.Close();
                    networkStream.Close();
                    //tcpListener.Stop();

                    // handlerSocketAuthenticate.Close();

                }
            }
            catch
            {
                Console.WriteLine("Cant send");
            }
        }

        else if (dataReceived.Equals("downloadfile"))
        {
            // handlerSocketAuthenticate.Close();
            // tcpListener.Stop();
            networkStream.Close();
            thdListenerDownload = new Thread(new ThreadStart(listenerThreadDownloading));
            thdListenerDownload.Start();
        }

        else
        {
            String clientIP1 = handlerSocketCommands.RemoteEndPoint.ToString();
            int index = clientIP1.IndexOf(":");
            clientIP1 = clientIP1.Substring(0, index);
            // handlerSocketAuthenticate.Close();
            CommandExecutor(dataReceived, clientIP1);
        }
    }

0 个答案:

没有答案