// MastersProjectDlg.cpp : implementation file // #include "stdafx.h" #include "MastersProject.h" #include "IPAddDlg.h" #include "utils.h" #include "xml.h" #include "MastersProjectDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CRITICAL_SECTION cs; SOCKET listener, clientSocket, serverSocket; ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMastersProjectDlg dialog CMastersProjectDlg::CMastersProjectDlg(CWnd* pParent /*=NULL*/) : CDialog(CMastersProjectDlg::IDD, pParent) { try { //{{AFX_DATA_INIT(CMastersProjectDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); initializeSockets(); }catch (std::string exception) { ::MessageBox(NULL, exception.c_str(), "Application Error", MB_ICONERROR); } } void CMastersProjectDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMastersProjectDlg) DDX_Control(pDX, IDCANCEL, m_exitButton); DDX_Control(pDX, IDC_BUTTON_CONNECT, m_connectButton); DDX_Control(pDX, IDC_PROGRESS_TRANSFER, m_transferProgress); DDX_Control(pDX, IDC_BUTTON_RECEIVE, m_receiveButton); DDX_Control(pDX, IDC_BUTTON_SEND, m_sendButton); DDX_Control(pDX, IDC_LIST_FILES_CLIENT, m_listFilesClient); DDX_Control(pDX, IDC_LIST_FILES_SERVER, m_listFilesServer); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMastersProjectDlg, CDialog) //{{AFX_MSG_MAP(CMastersProjectDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_NOTIFY(LVN_GETDISPINFO, IDC_LIST_FILES_SERVER, OnGetdispinfoListFilesServer) ON_NOTIFY(NM_DBLCLK, IDC_LIST_FILES_SERVER, OnDblclkListFilesServer) ON_NOTIFY(NM_CLICK, IDC_LIST_FILES_SERVER, OnClickListFilesServer) ON_BN_CLICKED(IDC_BUTTON_SEND, OnButtonSend) ON_BN_CLICKED(IDC_BUTTON_CONNECT, OnButtonConnect) ON_NOTIFY(LVN_GETDISPINFO, IDC_LIST_FILES_CLIENT, OnGetdispinfoListFilesClient) ON_NOTIFY(NM_DBLCLK, IDC_LIST_FILES_CLIENT, OnDblclkListFilesClient) ON_BN_CLICKED(IDC_BUTTON_RECEIVE, OnButtonReceive) ON_NOTIFY(NM_CLICK, IDC_LIST_FILES_CLIENT, OnClickListFilesClient) ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMastersProjectDlg message handlers BOOL CMastersProjectDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } OnButtonConnect(); th[0] = (HANDLE)_beginthread(startServer, 0, (void*) this); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon m_ilSmall.Create(IDB_SMALLDOC, 16, 2, RGB(255, 0, 255)); m_bmpSmallFolder.LoadBitmap(IDB_SMALLFOLDER); m_ilSmall.Add(&m_bmpSmallFolder, RGB(255, 0, 255)); // Setting the list controls m_listFilesServer.SetImageList(&m_ilSmall, LVSIL_SMALL); m_listFilesServer.InsertColumn(0, _T ("File Name"), LVCFMT_LEFT, 150); m_listFilesServer.InsertColumn(1, _T ("Size"), LVCFMT_RIGHT, 50); m_listFilesServer.InsertColumn(2, _T ("Last Modified"), LVCFMT_CENTER, 100); m_listFilesClient.SetImageList(&m_ilSmall, LVSIL_SMALL); m_listFilesClient.InsertColumn(0, _T ("File Name"), LVCFMT_LEFT, 150); m_listFilesClient.InsertColumn(1, _T ("Size"), LVCFMT_RIGHT, 50); m_listFilesClient.InsertColumn(2, _T ("Last Modified"), LVCFMT_CENTER, 100); TCHAR szPath[MAX_PATH]; ::GetCurrentDirectory( sizeof(szPath) / sizeof(TCHAR), szPath ); RefreshServer(szPath); return TRUE; // return TRUE unless you set the focus to a control } void CMastersProjectDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMastersProjectDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMastersProjectDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } int CMastersProjectDlg::RefreshServer(LPCTSTR pszPath) { CString strPathServer = pszPath; if (strPathServer.Right (1) != _T ("\\")) strPathServer += _T ("\\"); strPathServer += _T ("*.*"); HANDLE hFind; WIN32_FIND_DATA fd; int nCount = 0; if ((hFind = ::FindFirstFile (strPathServer, &fd)) != INVALID_HANDLE_VALUE) { // // Delete existing items (if any). // m_listFilesServer.DeleteAllItems (); // // Show the path name in the frame window's title bar. // TCHAR szFullPath[MAX_PATH]; ::GetFullPathName (pszPath, sizeof (szFullPath) / sizeof (TCHAR), szFullPath, NULL); m_strPathServer = szFullPath; CString strTitle = _T ("Masters Project - "); strTitle += szFullPath; AfxGetMainWnd ()->SetWindowText (strTitle); // // Add items representing files to the list view. // while (::FindNextFile (hFind, &fd)) if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) if (!AddItemServer (nCount++, &fd)) break; if ((hFind = ::FindFirstFile (strPathServer, &fd)) != INVALID_HANDLE_VALUE) while (::FindNextFile (hFind, &fd)) if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) if (!AddItemServer (nCount++, &fd)) break; ::FindClose (hFind); } return nCount; } BOOL CMastersProjectDlg::AddItemClient(int nIndex, WIN32_FIND_DATA *pfd) { // // Allocate a new ITEMINFO structure and initialize it with information // about the item. // ITEMINFO* pItem; try { pItem = new ITEMINFO; } catch (CMemoryException* e) { e->Delete (); return FALSE; } pItem->strFileName = pfd->cFileName; pItem->nFileSizeLow = pfd->nFileSizeLow; pItem->ftLastWriteTime = pfd->ftLastWriteTime; // // Add the item to the list view. // LV_ITEM lvi; lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; lvi.iItem = nIndex; lvi.iSubItem = 0; lvi.pszText = LPSTR_TEXTCALLBACK; lvi.lParam = (LPARAM) pItem; if (pfd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) lvi.iImage = 1; else lvi.iImage = 0; if (m_listFilesClient.InsertItem (&lvi) == -1) return FALSE; return TRUE; } BOOL CMastersProjectDlg::AddItemServer(int nIndex, WIN32_FIND_DATA *pfd) { // // Allocate a new ITEMINFO structure and initialize it with information // about the item. // ITEMINFO* pItem; try { pItem = new ITEMINFO; } catch (CMemoryException* e) { e->Delete (); return FALSE; } pItem->strFileName = pfd->cFileName; pItem->nFileSizeLow = pfd->nFileSizeLow; pItem->ftLastWriteTime = pfd->ftLastWriteTime; // // Add the item to the list view. // LV_ITEM lvi; lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; lvi.iItem = nIndex; lvi.iSubItem = 0; lvi.pszText = LPSTR_TEXTCALLBACK; lvi.lParam = (LPARAM) pItem; if (pfd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) lvi.iImage = 1; else lvi.iImage = 0; if (m_listFilesServer.InsertItem (&lvi) == -1) return FALSE; return TRUE; } void CMastersProjectDlg::OnGetdispinfoListFilesServer(NMHDR* pNMHDR, LRESULT* pResult) { CString string; LV_DISPINFO* pDispInfo = (LV_DISPINFO*) pNMHDR; if (pDispInfo->item.mask & LVIF_TEXT) { ITEMINFO* pItem = (ITEMINFO*) pDispInfo->item.lParam; switch (pDispInfo->item.iSubItem) { case 0: // File name ::lstrcpy (pDispInfo->item.pszText, pItem->strFileName); break; case 1: // File size if (!(pItem->nFileSizeLow == 0)) { string.Format (_T ("%u"), pItem->nFileSizeLow); ::lstrcpy (pDispInfo->item.pszText, string); } break; case 2: // Date and time CTime time (pItem->ftLastWriteTime); BOOL pm = FALSE; int nHour = time.GetHour (); if (nHour == 0) nHour = 12; else if (nHour == 12) pm = TRUE; else if (nHour > 12) { nHour -= 12; pm = TRUE; } string = time.Format("%m/%d/%y (%I:%M"); string += pm ? _T ('p') : _T ('a'); string += ")"; ::lstrcpy (pDispInfo->item.pszText, string); break; } } *pResult = 0; } void CMastersProjectDlg::OnGetdispinfoListFilesClient(NMHDR* pNMHDR, LRESULT* pResult) { CString string; LV_DISPINFO* pDispInfo = (LV_DISPINFO*) pNMHDR; if (pDispInfo->item.mask & LVIF_TEXT) { ITEMINFO* pItem = (ITEMINFO*) pDispInfo->item.lParam; switch (pDispInfo->item.iSubItem) { case 0: { // File name std::string fileName = std::string (pItem->strFileName); std::string pathName = fileName.substr(0, fileName.find_last_of("\\")); m_strPathClient = CString (pathName.c_str()); std::string newFileName = fileName.substr(fileName.find_last_of("\\")+1, fileName.length()-fileName.find_last_of("\\")); CString _fileName = CString (newFileName.c_str()); ::lstrcpy (pDispInfo->item.pszText, _fileName); break; } case 1: // File size if (!(pItem->nFileSizeLow == 0)) { string.Format (_T ("%u"), pItem->nFileSizeLow); ::lstrcpy (pDispInfo->item.pszText, string); } break; case 2: // Date and time CTime time (pItem->ftLastWriteTime); BOOL pm = FALSE; int nHour = time.GetHour (); if (nHour == 0) nHour = 12; else if (nHour == 12) pm = TRUE; else if (nHour > 12) { nHour -= 12; pm = TRUE; } string = time.FormatGmt("%m/%d/%y (%I:%M"); string += pm ? _T ('p') : _T ('a'); string += ")"; ::lstrcpy (pDispInfo->item.pszText, string); break; } } *pResult = 0; } void CMastersProjectDlg::OnDblclkListFilesServer(NMHDR* pNMHDR, LRESULT* pResult) { POSITION pos = m_listFilesServer.GetFirstSelectedItemPosition(); if (pos == NULL) TRACE0("No items were selected!\n"); else { int nItem = m_listFilesServer.GetNextSelectedItem(pos); m_fileName = m_strPathServer + "\\" + m_listFilesServer.GetItemText(nItem, 0); } RefreshServer((LPCTSTR) m_fileName); *pResult = 0; } void CMastersProjectDlg::OnDblclkListFilesClient(NMHDR* pNMHDR, LRESULT* pResult) { POSITION pos = m_listFilesClient.GetFirstSelectedItemPosition(); if (pos == NULL) TRACE0("No items were selected!\n"); else { int nItem = m_listFilesClient.GetNextSelectedItem(pos); xmlElement xmlEle1, xmlEle2; xmlEle1.tag("msg_type"); xmlEle1.data("dir struct"); xmlDocument xmlDoc; xmlDoc.tag("Masters_Project"); xmlDoc.data(xmlEle1); xmlEle2.tag("file_name"); std::string pathName = std::string (m_strPathClient + "\\" + m_listFilesClient.GetItemText(nItem, 0)); xmlEle2.data(pathName); xmlDoc.data(xmlEle2); try { int numBytes = send(clientSocket, xmlDoc.str().c_str(), xmlDoc.str().length(), 0); if (numBytes != xmlDoc.str().length()) throwString("-- Not all bytes sent --", __FILE__, __LINE__); }catch (std::string exception) { ::MessageBox(NULL, exception.c_str(), "Application Error", MB_ICONERROR); } } *pResult = 0; } void CMastersProjectDlg::OnClickListFilesServer(NMHDR* pNMHDR, LRESULT* pResult) { POSITION pos = m_listFilesServer.GetFirstSelectedItemPosition(); if (pos == NULL) { m_fileName = ""; m_sendButton.EnableWindow(FALSE); TRACE0("No items were selected!\n"); }else { int nItem = m_listFilesServer.GetNextSelectedItem(pos); if (!(m_listFilesServer.GetItemText(nItem, 1).Compare("") == 0)) { m_fileName = m_listFilesServer.GetItemText(nItem, 0); m_sendButton.EnableWindow(); } else m_sendButton.EnableWindow(FALSE); } *pResult = 0; } void CMastersProjectDlg::OnClickListFilesClient(NMHDR* pNMHDR, LRESULT* pResult) { POSITION pos = m_listFilesClient.GetFirstSelectedItemPosition(); if (pos == NULL) { m_fileName = ""; m_receiveButton.EnableWindow(FALSE); TRACE0("No items were selected!\n"); }else { int nItem = m_listFilesClient.GetNextSelectedItem(pos); if (!(m_listFilesClient.GetItemText(nItem, 1).Compare("") == 0)) { m_fileName = m_listFilesClient.GetItemText(nItem, 0); m_receiveButton.EnableWindow(); } else m_receiveButton.EnableWindow(FALSE); } *pResult = 0; } void CMastersProjectDlg::OnButtonReceive() { try { enableAll(FALSE); xmlElement xmlEle1, xmlEle2; xmlEle1.tag("msg_type"); xmlEle1.data("request"); xmlDocument xmlDoc; xmlDoc.tag("Masters_Project"); xmlDoc.data(xmlEle1); xmlEle2.tag("file_name"); std::string clientFileName = std::string (m_strPathClient) + "\\" + getFileName(); xmlEle2.data(clientFileName); xmlDoc.data(xmlEle2); int numBytes = send(clientSocket, xmlDoc.str().c_str(), xmlDoc.str().length(), 0); if (numBytes != xmlDoc.str().length()) throwString("-- Not all bytes sent --", __FILE__, __LINE__); }catch (std::string exception) { ::MessageBox(NULL, exception.c_str(), "Application Error", MB_ICONERROR); deleteClientList(); OnButtonConnect(); } } void CMastersProjectDlg::OnButtonConnect() { CString buttonName; m_connectButton.GetWindowText(buttonName); if (buttonName.Compare("Connect") == 0) { if (connectToServer()) m_connectButton.SetWindowText(_T ("Disconnect")); } else if (buttonName.Compare("Disconnect") == 0) { m_connectButton.SetWindowText(_T ("Connect")); deleteClientList(); closesocket(clientSocket); } } void CMastersProjectDlg::OnButtonSend() { std::string msg = "Error check"; if ((send (clientSocket, msg.c_str(), msg.length(), 0) != SOCKET_ERROR) && (m_fileName != "")) { std::string serverFileName = std::string (m_strPathServer) + "\\" + getFileName(); fileHandle = CreateFile(serverFileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); sendFileToClient(); } } void CMastersProjectDlg::sendFileToClient() { try { if (fileHandle) { DWORD fileSize = GetFileSize(fileHandle, NULL); m_transferProgress.SetRange32(0, fileSize); xmlElement xmlEle1, xmlEle2; xmlEle1.tag("msg_type"); xmlEle1.data("send"); xmlDocument xmlDoc; xmlDoc.tag("Masters_Project"); xmlDoc.data(xmlEle1); xmlEle2.tag("file_name"); std::string clientFileName = std::string (m_strPathClient) + "\\" + getFileName(); xmlEle2.data(clientFileName); xmlDoc.data(xmlEle2); std::string msg = xmlDoc.str(OPEN)+""; int numBytes = send(clientSocket, msg.c_str(), msg.length(), 0); if (numBytes != msg.length()) throwString("-- Not all bytes sent --", __FILE__, __LINE__); th[5] = (HANDLE)_beginthread(sendFile, 0, (void*) this); } }catch (std::string exception) { ::MessageBox(NULL, exception.c_str(), "Application Error", MB_ICONERROR); CloseHandle(fileHandle); } } void _cdecl sendFile(void* pArgs) { CMastersProjectDlg* pClient = (CMastersProjectDlg*) pArgs; pClient->enableAll(FALSE); try { const int bytestoRead = 256; int numBytes; char buff[bytestoRead]; unsigned long bytesRead = -1; BOOL bResult = 1; int count = 0; while ( bResult && bytesRead != 0 ) { for (int i=0; i<256; i++) buff[i] = '\0'; std::string fileCont = ""; bResult = ReadFile (pClient->getFileHandle(), buff, bytestoRead, &bytesRead, NULL); for (i=0; isetProgressPos(count); } } numBytes = send(clientSocket, "", 30, 0); CloseHandle(pClient->getFileHandle()); }catch (std::string exception) { ::MessageBox(NULL, exception.c_str(), "Application Error", MB_ICONERROR); pClient->enableAll(); pClient->setProgressPos(0); CloseHandle(pClient->getFileHandle()); } } bool CMastersProjectDlg::connectToServer() { CIPAddDlg _IPAddDlg; if (_IPAddDlg.DoModal() == IDOK) { CString _IPAdd = _IPAddDlg.getIPAdd(); _IPAdd.TrimRight(); std::string IPAdd = std::string(_IPAdd); if (IPAdd.compare("0.0.0.0") != 0) { try { /////////////////////////////////////////////////////////////////// // create TCP/IP socket object clientSocket = createSocket(); /////////////////////////////////////////////////////////////////// // connect to server on specified address and port // - note the IP address 127.0.0.1 refers to host machine int port = 1024; // user port SOCKADDR_IN tcpAddr; tcpAddr.sin_family = AF_INET; // TCP/IP tcpAddr.sin_addr.s_addr = inet_addr(IPAdd.c_str()); // host machine tcpAddr.sin_port = htons(port); // server port if (connect(clientSocket, (sockaddr*)&tcpAddr, sizeof(tcpAddr)) == SOCKET_ERROR) throwString("Connection error type:", __FILE__, __LINE__); th[1] = (HANDLE)_beginthread(serverListener, 0, (void*) this); th[2] = (HANDLE)_beginthread(deQSenderTh, 0, (void*) this); xmlElement xmlEle1, xmlEle2; xmlEle1.tag("msg_type"); xmlEle1.data("dir struct"); xmlDocument xmlDoc; xmlDoc.tag("Masters_Project"); xmlDoc.data(xmlEle1); xmlEle2.tag("file_name"); xmlEle2.data("root"); xmlDoc.data(xmlEle2); int numBytes = send(clientSocket, xmlDoc.str().c_str(), xmlDoc.str().length(), 0); if (numBytes != xmlDoc.str().length()) throwString("-- Not all bytes sent --", __FILE__, __LINE__); return true; }catch (std::string exception) { ::MessageBox(NULL, exception.c_str(), "Application Error", MB_ICONERROR); return false; } }else return false; }else return false; return false; } void _cdecl startServer(void* pArgs) { CMastersProjectDlg* pClient = (CMastersProjectDlg*) pArgs; try { initializeSockets(); /////////////////////////////////////////////////////////////////// // create TCP/IP socket object to listen for connection requests listener = createSocket(); /////////////////////////////////////////////////////////////////// // bind listner socket to specific port and network interface int port = 1024; SOCKADDR_IN tcpAddr; tcpAddr.sin_family = AF_INET; // TCP/IP tcpAddr.sin_port = htons(port); // listening port tcpAddr.sin_addr.s_addr = INADDR_ANY; // listen over every network interface if(bind(listener, (SOCKADDR*)&tcpAddr, sizeof(tcpAddr)) == SOCKET_ERROR) throwString("Connection error type:", __FILE__, __LINE__); /////////////////////////////////////////////////////////////////// // listen for incoming connection requests if(listen(listener, SOMAXCONN) == SOCKET_ERROR) throwString("Connection error type:", __FILE__, __LINE__); /////////////////////////////////////////////////////////////////// // block until a connection is established int size = sizeof(tcpAddr); std::string msg = "Error check"; while(1) { SOCKET toClient = accept(listener, (SOCKADDR*)&tcpAddr, &size); if(toClient == INVALID_SOCKET) break; if (send(serverSocket, msg.c_str(), msg.length(), 0) == SOCKET_ERROR) { serverSocket = toClient; pClient->getHandle(3) = (HANDLE)_beginthread(enQListenerTh, 0,(void*) pClient ); pClient->getHandle(4) = (HANDLE)_beginthread(deQListenerTh, 0,(void*) pClient ); } } /////////////////////////////////////////////////////////////////// // close down gracefully closesocket(listener); cleanUpSockets(); }catch (std::string exception) { MessageBox(NULL, exception.c_str(), "Application Error", MB_ICONERROR); } } void _cdecl deQSenderTh(void* pArgs) { CMastersProjectDlg* pClient = (CMastersProjectDlg*) pArgs; const int bytesToWrite = 251; unsigned long bytesWritten = -1; std::string deQString; std::string recvdMsg = ""; while (deQString.compare("Suicide") != 0) { while (pClient->lenQSender() == 0) Sleep(50); EnterCriticalSection(&cs); deQString = pClient->deQSender(); LeaveCriticalSection(&cs); if (deQString.find("") != -1) { recvdMsg = deQString; if (recvdMsg.find("send") == -1) { while (deQString.find("") == -1) { while (pClient->lenQSender() == 0) Sleep(50); EnterCriticalSection(&cs); deQString = pClient->deQSender(); recvdMsg += deQString; LeaveCriticalSection(&cs); } xmlParse parse(recvdMsg); parse.accept(parse.dataStr()); int count = 0; if (parse.dataStr().compare("dir struct") == 0) { pClient->deleteClientList(); while (parse.next()) { WIN32_FIND_DATA* fd = new WIN32_FIND_DATA; xmlParse fileDet(parse.dataStr()); if (fileDet.tagStr().compare("name") == 0) { CString fileName = CString (fileDet.dataStr().c_str()); for (int i=0; icFileName[i] = fileName.GetAt(i); } fd->cFileName[fileName.GetLength()] = '\0'; } while (fileDet.next()) { if (fileDet.tagStr().compare("size") == 0) { int fileSize = atoi(fileDet.dataStr().c_str());; fd->nFileSizeLow = fileSize; if (fileSize == 0) fd->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY; } else if (fileDet.tagStr().compare("time") == 0) { std::string timeStr = fileDet.dataStr(); int month = atoi(timeStr.substr(0, timeStr.find_first_of("//")).c_str()); timeStr.erase(0, timeStr.find_first_of("//")+1); int day = atoi(timeStr.substr(0, timeStr.find_first_of("//")).c_str()); timeStr.erase(0, timeStr.find_first_of("//")+1); int year = atoi(timeStr.substr(0, timeStr.find_first_of("(")-1).c_str()); if ((year > 38) && (year < 100)) year += 1900; else year += 2000; timeStr.erase(0, timeStr.find_first_of("(")+1); int hours = atoi(timeStr.substr(0, timeStr.find_first_of(":")).c_str()); timeStr.erase(0, timeStr.find_first_of(":")+1); int minutes = atoi(timeStr.substr(0, timeStr.find_first_of(")")-1).c_str()); char ampm = timeStr.at(timeStr.find_first_of(")")-1); switch(ampm) { case 'a': if (hours == 12) hours = 0; break; case 'p': if (hours != 12) hours += 12; break; } CTime time (year, month, day, hours, minutes, 0); SYSTEMTIME timeDest; time.GetAsSystemTime(timeDest); ::SystemTimeToFileTime(&timeDest, &fd->ftLastWriteTime); } } pClient->AddItemClient(count, fd); count++; parse.next();parse.next();parse.next(); } } }else { HANDLE hFile = NULL; int count = 0; DWORD fileSize; if (deQString.find("file_name") != -1) { std::string fileName; parser parseFN(deQString); parseFN.getData("file_name", fileName); fileName = fileName.substr(fileName.find_last_of("\\")+1, fileName.length()-1); std::string size = fileName.substr(fileName.find(";")+1, fileName.length()-fileName.find(";")+1); fileSize = atoi(size.c_str()); fileName.erase(fileName.find(";"), fileName.length()-fileName.find(";")); fileName.insert(0, pClient->getServerPath()+"\\"); hFile = CreateFile(fileName.c_str(),GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); } if (hFile) pClient->setProgressRange(0, fileSize); while ((deQString.find("") == -1) && (deQString.compare("Suicide") != 0)) { while (pClient->lenQSender() == 0) Sleep(50); EnterCriticalSection(&cs); deQString = pClient->deQSender(); LeaveCriticalSection(&cs); while ((deQString.length()%4 != 0) && (deQString.find("") == -1)) { while (pClient->lenQSender() == 0) Sleep(50); EnterCriticalSection(&cs); deQString += pClient->deQSender(); LeaveCriticalSection(&cs); } std::string outString; if (deQString.find("<") == -1) { for ( int i=0; isetProgressPos(count); }else { int pos = deQString.find("<"); for (int i=0; isetProgressPos(count); } } if (hFile) CloseHandle(hFile); pClient->enableAll(); pClient->RefreshServer(pClient->getServerPath().c_str()); pClient->setProgressPos(0); } } } } void _cdecl enQListenerTh(void* pArgs) { CMastersProjectDlg* pClient = (CMastersProjectDlg*) pArgs; std::string save; const int bufSize = 1024; int bytes, count=0; do { char buffer[bufSize]; bytes = recv(serverSocket,buffer,bufSize-1,0); buffer[bytes] = '\0'; save = buffer; if(bytes > 0) { EnterCriticalSection(&cs); pClient->enQListener(save); LeaveCriticalSection(&cs); } } while(bytes != 0 && bytes != SOCKET_ERROR); try { if(bytes == SOCKET_ERROR) throwString("Receive error type: ", __FILE__, __LINE__); pClient->enQListener("Suicide"); }catch (std::string exception) { pClient->enQListener("Suicide"); } if (serverSocket != INVALID_SOCKET) closesocket(serverSocket); } void _cdecl deQListenerTh(void* pArgs) { CMastersProjectDlg* pHClient = (CMastersProjectDlg*) pArgs; int count=0; BOOL start = FALSE; std::string _tempBin = ""; const int bytesToWrite = 251; unsigned long bytesWritten = -1; std::string deQString; try { while(deQString.compare("Suicide") != 0) { while (pHClient->lenQListener() == 0) Sleep(50); EnterCriticalSection(&cs); deQString = pHClient->deQListener(); LeaveCriticalSection(&cs); if (deQString.find("send") != -1) { HANDLE hFile = NULL; std::string fileName; while ((deQString.find("") == -1) && (deQString.compare("Suicide") != 0)) { if (deQString.find("file_name") != -1) { parser parseFN(deQString); parseFN.getData("file_name", fileName); hFile = CreateFile(fileName.c_str(),GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); } while (pHClient->lenQListener() == 0) Sleep(50); EnterCriticalSection(&cs); deQString = pHClient->deQListener(); LeaveCriticalSection(&cs); while ((deQString.length()%4 != 0) && (deQString.find("") == -1)) { while (pHClient->lenQListener() == 0) Sleep(50); EnterCriticalSection(&cs); deQString += pHClient->deQListener(); LeaveCriticalSection(&cs); } std::string outString; if (deQString.find("<") == -1) { for ( int i=0; igetXMLDirStruct(pathName); int numBytesSent = send(serverSocket, XMLString.c_str(), XMLString.length(), 0); if(numBytesSent != XMLString.length()) throwString("-- Not all bytes sent --", __FILE__, __LINE__); }else { xmlParse parse(deQString); parse.accept(parse.dataStr()); std::string fileName; if (parse.dataStr().compare("dir struct") == 0) { if (parse.next()) if (parse.tagStr().compare("file_name") == 0) fileName = parse.dataStr(); if (fileName.compare("root") == 0) { TCHAR szPath[MAX_PATH]; ::GetCurrentDirectory( sizeof(szPath) / sizeof(TCHAR), szPath ); fileName = std::string(szPath); } TCHAR szFullPath[MAX_PATH]; ::GetFullPathName (fileName.c_str(), sizeof (szFullPath) / sizeof (TCHAR), szFullPath, NULL); fileName = szFullPath; std::string XMLString = pHClient->getXMLDirStruct(fileName); int numBytesSent = send(serverSocket, XMLString.c_str(), XMLString.length(), 0); if(numBytesSent != XMLString.length()) throwString("-- Not all bytes sent --", __FILE__, __LINE__); }else if (parse.dataStr().compare("request") == 0) { if (parse.next()) if (parse.tagStr().compare("file_name") == 0) fileName = parse.dataStr(); HANDLE hFile = CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); DWORD fileSize = GetFileSize(hFile, NULL); char _buff[10]; itoa(fileSize, _buff, 10); const int bytestoRead = 256; char buff[bytestoRead]; unsigned long bytesRead = -1; BOOL bResult = 1; if (hFile) { xmlElement xmlEle1, xmlEle2; xmlEle1.tag("msg_type"); xmlEle1.data("send"); xmlDocument xmlDoc; xmlDoc.tag("Masters_Project"); xmlDoc.data(xmlEle1); xmlEle2.tag("file_name"); std::string fileNameAndSize = fileName; fileNameAndSize += ";"; fileNameAndSize += _buff; xmlEle2.data(fileNameAndSize); xmlDoc.data(xmlEle2); std::string msg = xmlDoc.str(OPEN)+""; int numBytes = send(serverSocket, msg.c_str(), msg.length(), 0); if (numBytes != msg.length()) throwString("-- Not all bytes sent --", __FILE__, __LINE__); while ( bResult && bytesRead != 0 ) { for (int i=0; i<256; i++) buff[i] = '\0'; std::string fileCont = ""; bResult = ReadFile (hFile, buff, bytestoRead, &bytesRead, NULL); for (i=0; i", 30, 0); } CloseHandle(hFile); } } } }catch (std::string exception) { ::MessageBox(NULL, exception.c_str(), "Application Error", MB_ICONERROR); } } void _cdecl serverListener(void* pArgs) { CMastersProjectDlg* pClient = (CMastersProjectDlg*) pArgs; std::string save; const int bufSize = 1024; int bytes, count=0; do { char buffer[bufSize]; bytes = recv(clientSocket,buffer,bufSize-1,0); buffer[bytes] = '\0'; save = buffer; if(bytes > 0) { EnterCriticalSection(&cs); pClient->enQSender(save); LeaveCriticalSection(&cs); } } while(bytes != 0 && bytes != SOCKET_ERROR); try { if(bytes == SOCKET_ERROR) throwString("Receive error type: ", __FILE__, __LINE__); pClient->enQSender("Suicide"); }catch (std::string exception) { pClient->enQSender("Suicide"); } if (clientSocket != INVALID_SOCKET) closesocket(clientSocket); } void CMastersProjectDlg::deleteClientList() { m_transferProgress.SetPos(0); enableAll(); m_listFilesClient.DeleteAllItems(); } std::string CMastersProjectDlg::getXMLDirStruct(std::string fileName) { HANDLE hFind; WIN32_FIND_DATA fd; xmlDocument doc; if (fileName.substr(fileName.length()-2, 1) != "\\") fileName += "\\"; fileName += "*.*"; if ((hFind = ::FindFirstFile(fileName.c_str(), &fd)) != INVALID_HANDLE_VALUE) { doc.tag("Masters_Project"); xmlElement xmlEle5; xmlEle5.tag("msg_type"); xmlEle5.data("dir struct"); doc.data(xmlEle5); while (::FindNextFile (hFind, &fd)) if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { xmlElement xmlEle1, xmlEle2, xmlEle3, xmlEle4; xmlEle1.tag("file"); xmlEle2.tag("name"); xmlEle2.data(fileName.substr(0, fileName.length()-3)+fd.cFileName); xmlEle3.tag("size"); xmlEle4.tag("time"); CTime time (fd.ftLastWriteTime); BOOL pm = FALSE; int nHour = time.GetHour (); if (nHour == 0) nHour = 12; else if (nHour == 12) pm = TRUE; else if (nHour > 12) { nHour -= 12; pm = TRUE; } CString string; string.Format (_T ("%d/%0.2d/%0.2d (%d:%0.2d%c)"), time.GetMonth (), time.GetDay (), time.GetYear () % 100, nHour, time.GetMinute (), pm ? _T ('p') : _T ('a')); std::string fileDet = std::string(string); xmlEle4.data(fileDet); xmlEle1.data(xmlEle2); xmlEle1.data(xmlEle3); xmlEle1.data(xmlEle4); doc.data(xmlEle1); } if ((hFind = ::FindFirstFile (fileName.c_str(), &fd)) != INVALID_HANDLE_VALUE) while (::FindNextFile (hFind, &fd)) if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { xmlElement xmlEle1, xmlEle2, xmlEle3, xmlEle4; xmlEle1.tag("file"); xmlEle2.tag("name"); xmlEle2.data(fileName.substr(0, fileName.length()-3)+fd.cFileName); xmlEle3.tag("size"); CString string; string.Format (_T ("%u"), fd.nFileSizeLow); std::string fileDet = std::string(string); xmlEle3.data(fileDet); xmlEle4.tag("time"); CTime time (fd.ftLastWriteTime); BOOL pm = FALSE; int nHour = time.GetHour (); if (nHour == 0) nHour = 12; else if (nHour == 12) pm = TRUE; else if (nHour > 12) { nHour -= 12; pm = TRUE; } string.Format (_T ("%d/%0.2d/%0.2d (%d:%0.2d%c)"), time.GetMonth (), time.GetDay (), time.GetYear () % 100, nHour, time.GetMinute (), pm ? _T ('p') : _T ('a')); fileDet = std::string(string); xmlEle4.data(fileDet); xmlEle1.data(xmlEle2); xmlEle1.data(xmlEle3); xmlEle1.data(xmlEle4); doc.data(xmlEle1); } } ::FindClose (hFind); return doc.str(); } void CMastersProjectDlg::setProgressRange(int nLower, int nUpper) { m_transferProgress.SetRange32(nLower, nUpper); } void CMastersProjectDlg::setProgressPos(int nPos) { m_transferProgress.SetPos(nPos); } void CMastersProjectDlg::enableAll(BOOL show) { BOOL buttonShowServer = show, buttonShowClient = show; if (show) { buttonShowServer = m_listFilesServer.GetFirstSelectedItemPosition() ? TRUE : FALSE; buttonShowClient = m_listFilesClient.GetFirstSelectedItemPosition() ? TRUE : FALSE; } m_sendButton.EnableWindow(buttonShowServer); m_receiveButton.EnableWindow(buttonShowClient); m_connectButton.EnableWindow(show); m_exitButton.EnableWindow(show); m_listFilesServer.EnableWindow(show); m_listFilesClient.EnableWindow(show); } void CMastersProjectDlg::OnDestroy() { CDialog::OnDestroy(); std::string msg = "Error check"; enQSender("Suicide"); WaitForMultipleObjects(6, th, TRUE, INFINITE); if (clientSocket != INVALID_SOCKET) closesocket(clientSocket); cleanUpSockets(); }