多线程FTP服务器套接字VC ++

时间:2014-09-30 14:17:42

标签: multithreading sockets visual-c++ ftp

我正在VC ++中用多线程编写一个基本的FTP客户端服务器代码。

该代码适用于单个客户端,但它不适用于2个客户端。我不知道socket如何为多个客户端保留信息。 如果我从客户端做CD,它也反映在另一个。我的意思是,如果两个不同的客户端无法在不同的服

由于我对套接字编程缺乏了解,可能是我在这里缺少的基础。

接受连接的代码:

   void acceptUserConnections()
{
    calen=sizeof(ca);
    int thread_count = 0;
    thread t[num_threads];

    while(1)
    {
            cout<<"Accepting user connections: "<<endl;
            if((cs=accept(serverSocket,&ca.generic,&calen))==INVALID_SOCKET)
                throw "Couldn't accept connection\n";

            string userAddress(inet_ntoa(ca.ca_in.sin_addr));

            thread_count = thread_count +1;
            t[thread_count] = thread(handleUserConnection, cs);
            t[thread_count].detach();
            //handleUserConnection(clientSocket);
        }
    }
}

处理:

        void handleUserConnection(SOCKET clientSocket)
{
           if (strcmpi(command.c_str(),"PWD")==0)
            {
                ftpPWD(clientSocket);
            }
}

for CD

    void ftpCD(string directory, SOCKET clientSocket)
{
        memset(szbuffer,'\0',1024);
        if(!SetCurrentDirectory(directory.c_str()))
        {
            cout<<strerror(errno)<<endl;
            sprintf(szbuffer,"System cannot find the specified directory.");
            if(send(clientSocket,szbuffer,1024,0) == SOCKET_ERROR)
                throw SEND_FAILED_MSG;
        }
        else
        {
            sprintf(szbuffer,"Directory changed successfully.");
            if(send(clientSocket,szbuffer,1024,0) == SOCKET_ERROR)
                throw SEND_FAILED_MSG;
        }

}

for PWD

void ftpPWD(SOCKET clientSocket)
{
        memset(szbuffer,'\0',1024);
        int nBufferLength =GetCurrentDirectory(MAX_PATH, pwd);
        if(!nBufferLength)
        {
            sprintf(szbuffer,"Failed to get current directory");
            if(send(clientSocket,szbuffer,1024,0) == SOCKET_ERROR )
                throw SEND_FAILED_MSG;
        }
        else
        {
            sprintf(szbuffer,(string(pwd)).c_str());
            if(send(clientSocket,szbuffer,1024,0) == SOCKET_ERROR )
                throw SEND_FAILED_MSG;
        }
    }
}

0 个答案:

没有答案