// server.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "winsock2.h"
#include "server.h"
#include "serverDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// CServerApp
BEGIN_MESSAGE_MAP(CServerApp, CWinApp)
//{{AFX_MSG_MAP(CServerApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/
// CServerApp construction
CServerApp::CServerApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/
// The one and only CServerApp object
CServerApp theApp;
/
// CServerApp initialization
BOOL CServerApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CServerDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
// server.h : main header file for the SERVER application
//
#if !defined(AFX_SERVER_H__3D0F92B0_603A_4906_B31F_770FB2AF3BF9__INCLUDED_)
#define AFX_SERVER_H__3D0F92B0_603A_4906_B31F_770FB2AF3BF9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/
// CServerApp:
// See server.cpp for the implementation of this class
//
class CServerApp : public CWinApp
{
public:
CServerApp();
int num;
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CServerApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CServerApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SERVER_H__3D0F92B0_603A_4906_B31F_770FB2AF3BF9__INCLUDED_)
// serverDlg.cpp : implementation file
//
#include "stdafx.h"
#include "iostream"
#include "winsock2.h"
#include "mswsock.h"
#include "server.h"
#include "serverDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// CAboutDlg dialog used for App About
UINT LStreadproc(LPVOID lpParam); //监听线程
UINT AStreadproc(LPVOID lParam); //接收线程
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()
/
// CServerDlg dialog
CServerDlg::CServerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CServerDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CServerDlg)
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CServerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CServerDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CServerDlg, CDialog)
//{{AFX_MSG_MAP(CServerDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_CLOSE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/
// CServerDlg message handlers
BOOL CServerDlg::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);
}
}
// 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
LSeventnum=0; //监听事件总数
ASeventnum=0; //接收事件总数
recvnums=0; //接收的数据大小
ZeroMemory(&ASoverlapped,sizeof(WSAOVERLAPPED));
// TODO: Add extra initialization here
WSADATA wsadata;
WSAStartup(MAKEWORD(2,2),&wsadata);
listensock=WSASocket(AF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED);
acceptsock=WSASocket(AF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED);
SOCKADDR_IN sockaddr;
sockaddr.sin_family=AF_INET;
sockaddr.sin_addr.s_addr=htonl(ADDR_ANY);
sockaddr.sin_port=htons(8589);
bind(listensock,(PSOCKADDR)&sockaddr,sizeof(sockaddr));
listen(listensock,1);
if (WSAGetLastError()!=0)
{
AfxMessageBox("SOCKET初始化失败!");
SendMessage(WM_CLOSE,0,0);
}
LSeventarray[LSeventnum]=WSACreateEvent();
ZeroMemory(&LSoverlapped,sizeof(WSAOVERLAPPED));
LSoverlapped.hEvent=LSeventarray[LSeventnum]; //负责监听的事件
LSeventnum++;
AcceptEx(listensock,acceptsock,(PVOID)&LSbuffer,0,32,32,NULL,&LSoverlapped);
if (WSAGetLastError()!=997)
{
AfxMessageBox("监听端口重叠操作失败");
SendMessage(WM_CLOSE,0,0);
}
AfxBeginThread(LStreadproc,NULL);
return TRUE; // return TRUE unless you set the focus to a control
}
void CServerDlg::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 CServerDlg::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 CServerDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
UINT LStreadproc(LPVOID lpParam)
{
DWORD dindex;
SOCKADDR_IN REaddr;
int addrlen;
CServerDlg *app=(CServerDlg*)AfxGetApp()->GetMainWnd(); //取得主窗口^_^想访问他的数据很久了
dindex=WSAWaitForMultipleEvents(app->LSeventnum,app->LSeventarray,FALSE,WSA_INFINITE,FALSE);
dindex=dindex-WSA_WAIT_EVENT_0; //这才是真正的事件序号
WSAResetEvent(app->LSeventarray[dindex]);
accept(app->acceptsock,(PSOCKADDR)&REaddr,&addrlen);//还是这个函数拿来好用
LPCTSTR lpip=inet_ntoa(REaddr.sin_addr); //得到连接的IP地址
AfxBeginThread(AStreadproc,NULL);
return 0;
}
UINT AStreadproc(LPVOID lParam)
{
int i;
int len;
char buffer[4096]; //数据缓冲
DWORD flags=0;
CString filelen;
CString filename;
DWORD dindex;
CString pathinfo;
CString fileinfo;
CServerDlg *app=(CServerDlg*)AfxGetApp()->GetMainWnd(); //多用GetLastError- -#防错是关键啊
ZeroMemory(buffer,4096); //初始化数据缓冲
app->wsabuf.buf=buffer;
app->wsabuf.len=4096;
app->ASeventarray[app->ASeventnum]=WSACreateEvent();
app->ASoverlapped.hEvent=app->ASeventarray[app->ASeventnum];
app->ASeventnum++; //接收的事件数目
char strdir[MAX_PATH];
char strpath[MAX_PATH];
BROWSEINFO bi={0};
bi.hwndOwner=app->GetSafeHwnd();
bi.pidlRoot=NULL;
bi.lpszTitle="请选择你要保存的路径";
bi.ulFlags=BIF_RETURNONLYFSDIRS|BIF_EDITBOX;
bi.pszDisplayName=strdir;
LPITEMIDLIST pidl=SHBrowseForFolder(&bi);
if (SHGetPathFromIDList(pidl,strpath))
{
pathinfo.Format("%s",strpath);
}
while (TRUE)
{
WSARecv(app->acceptsock,&app->wsabuf,1,&app->recvnums,&flags,&app->ASoverlapped,NULL); //投递一个接收消息的重叠结构
dindex=WSAWaitForMultipleEvents(app->ASeventnum,app->ASeventarray,FALSE,WSA_INFINITE,FALSE);
dindex-=WSA_WAIT_EVENT_0;
WSAResetEvent(app->ASeventarray[dindex]);
DWORD Drecvnum;
DWORD Dresult;
WSAGetOverlappedResult(app->acceptsock,&app->ASoverlapped,&Drecvnum,FALSE,&Dresult);
if (Drecvnum==0)
{
AfxMessageBox("端口关闭");
SendMessage(app->m_hWnd,WM_CLOSE,0,0);
}
CString str;
str.Format("%s",buffer);
i=str.Find("|",0);
if (str.GetLength()<=0||i==-1)
{
AfxMessageBox("文件发送格式有误");
SendMessage(app->m_hWnd,WM_CLOSE,0,0);
}
filename=str.Left(i);
filelen=str.Right(str.GetLength()-i-1);
len=atoi(filelen);
fileinfo=pathinfo+"//"+filename;
CFile file;
file.Open(fileinfo,CFile::modeReadWrite|CFile::modeCreate);
WSARecv(app->acceptsock,&app->wsabuf,1,&app->recvnums,&flags,&app->ASoverlapped,NULL);
while (TRUE)
{
dindex=WSAWaitForMultipleEvents(app->ASeventnum,app->ASeventarray,FALSE,WSA_INFINITE,FALSE);
dindex=dindex-WSA_WAIT_EVENT_0; //真正的事件序列
WSAResetEvent(app->ASeventarray[dindex]); //将事件重置一下留待下一次使用
WSAGetOverlappedResult(app->acceptsock,&app->ASoverlapped,&Drecvnum,FALSE,&Dresult); //- -#这个函数主要是用来取回发送数据大小的
len-=Drecvnum;
file.Write(buffer,Drecvnum);
if (!len)
{
file.Close();
send(app->acceptsock,"next",5,0);
break;
}
WSARecv(app->acceptsock,&app->wsabuf,1,&app->recvnums,&flags,&app->ASoverlapped,NULL);
}
}
return 0;
}
void CServerDlg::OnClose()
{
// TODO: Add your message handler code here and/or call default
closesocket(listensock);
closesocket(acceptsock);
//WSACloseEvent(LSeventarray[0]);
CDialog::OnClose();
}
// serverDlg.h : header file
//
#if !defined(AFX_SERVERDLG_H__68D1EBF0_3F75_4D7C_853B_E8DBAFF91C3A__INCLUDED_)
#define AFX_SERVERDLG_H__68D1EBF0_3F75_4D7C_853B_E8DBAFF91C3A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/
// CServerDlg dialog
class CServerDlg : public CDialog
{
// Construction
public:
CServerDlg(CWnd* pParent = NULL); // standard constructor
WSAEVENT LSeventarray[WSA_MAXIMUM_WAIT_EVENTS]; //监听消息数组
WSAEVENT ASeventarray[WSA_MAXIMUM_WAIT_EVENTS]; //接受消息数组
DWORD LSeventnum;
DWORD ASeventnum;
WSABUF wsabuf;//重叠模式下的数据缓冲
SOCKET acceptsock;
SOCKET listensock;
WSAOVERLAPPED ASoverlapped;
DWORD recvnums; //接收到的数据大小
WSAOVERLAPPED LSoverlapped;
char LSbuffer[64]; //监听端口的数据缓冲
// Dialog Data
//{{AFX_DATA(CServerDlg)
enum { IDD = IDD_SERVER_DIALOG };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CServerDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
WSAOVERLAPPED Loverlapped;
// Generated message map functions
//{{AFX_MSG(CServerDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnClose();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SERVERDLG_H__68D1EBF0_3F75_4D7C_853B_E8DBAFF91C3A__INCLUDED_)