⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ctsserverdlg.cpp

📁 码头手持机项目,用于统计集装箱,轮船的情况,手持机采用S3C2440处理器,数据传输采用2.4G无线,上位机用VC编写
💻 CPP
字号:
// CTSServerDlg.cpp : implementation file
//
#include <comutil.h>
#include "stdafx.h"
#include "CTSServer.h"
#include "CTSServerDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
#define ServerPort (u_short)4660
/////////////////////////////////////////////////////////////////////////////

extern CCTSServerApp theApp; 
//CString convert(BSTR b) 
//{
//    CString s;
//    if(b == NULL)
//        return s; // empty for NULL BSTR 
//    #ifdef UNICODE 
//        s = b;
//    #else
//        LPSTR p = s.GetBuffer(SysStringLen(b) + 1);
//    ::WideCharToMultiByte(CP_ACP, // ANSI Code Page
//         0, // no flags
//         b, // source widechar string
//        -1, // assume NUL-terminated
//         p, // target buffer
//         SysStringLen(b)+1, // target buffer length
//         NULL, // use system default char
//         NULL); // don't care if default used
//    s.ReleaseBuffer();
//    #endif
//    return s;
//}
/////////////////////////////////////////////////////////////////////////////
UINT Clientthread(void *cs)
{
	SOCKET clientSocket = (SOCKET)cs;
	int recvcount=0;
	int retint=0,retint2=0;
	CString sqlstr=_T("");
	variant_t RecordsAffected;
	CString strValue=_T("");
	CCTSServerApp* tp = (CCTSServerApp*)AfxGetApp();
	char sendbuf[10240];
	char sendbuf2[3072];
	int m_nResultCol=0,loop1=0,loop2=0;
	int datalength=0,totalnum=0;
	int bufnum1=0,bufnum2=0;
	int i=0,actint=0,temp1=0,temp2=0;
	//char recvBuf[512];
	char recvBuf[1024];
	int timeout=0;
	
	//test
	///////////////////////////
	char *psql;
	///////////////////////////
	
	_RecordsetPtr m_pRecordset;
	m_pRecordset.CreateInstance(__uuidof(Recordset));
	while (1)
	{
		//init
		///////////////////////////////////////
		recvcount=0;
		retint=0;
		retint2=0;
		actint=0;
		temp1=0;
		temp2=0;
		timeout=0;
		///////////////////////////////////////
		
		//retint=recv(clientSocket,recvBuf,512,0);
		retint=recv(clientSocket,recvBuf,1024,0);
		if (retint==0 || retint==-1)
		{
			closesocket(clientSocket);
			break;
		}
		temp1=recvBuf[1];
		if (temp1<0)
			temp1=temp1+256;
		temp2=recvBuf[2];
		if (temp2<0)
			temp2=temp2+256;
		actint=temp1*256+temp2;
		timeout=1000;
		setsockopt(clientSocket, SOL_SOCKET, SO_RCVTIMEO,(char*)&timeout,sizeof(int));
		while(retint!=actint)
		{
            //retint2=recv(clientSocket,recvBuf+retint,512-retint,0);
			retint2=recv(clientSocket,recvBuf+retint,1024-retint,0);
			retint=retint+retint2;
			recvcount++;
			if (recvcount==4)
			{
				recvcount=0;
				recvBuf[0]=0;
				sendbuf[0]=8;
				send(clientSocket,sendbuf,1,0);
				break;
			}
		}
		timeout=0;
		setsockopt(clientSocket, SOL_SOCKET, SO_RCVTIMEO,(char*)&timeout,sizeof(int));
		
		//test code begin
		//////////////////////////////////////////////////////////////////////////////
		psql=&recvBuf[3];
	    sqlstr = psql;
		sqlstr.Replace("'","*");
        sqlstr = "insert into transfersql values('"+sqlstr;
		sqlstr = sqlstr +"')";
		try
		{
			tp->m_cConn->Execute((_bstr_t)sqlstr,&RecordsAffected,adCmdText);
		}
		catch(_com_error *e)
		{
			AfxMessageBox(e->ErrorMessage());
		}
		//////////////////////////////////////////////////////////////////////////////
		//test code end
		
		if (recvBuf[0]==3)
		{
			recvBuf[0]=32;
			recvBuf[1]=32;
			recvBuf[2]=32;
			
			//init
			//////////////////////////////////
			sqlstr=_T("");
			strValue=_T("");
			m_nResultCol=0;
			loop1=0;
			loop2=0;
			datalength=0;
			totalnum=0;
			bufnum1=0;
			bufnum2=0;
			i=0;
			//////////////////////////////////
			
			sqlstr=recvBuf;
			
			try
			{
				m_pRecordset->CursorLocation=adUseClient;
				m_pRecordset->Open(_bstr_t(sqlstr),_variant_t((IDispatch*)tp->m_cConn,true),adOpenDynamic,adLockOptimistic,adCmdText);
			}
			catch(_com_error *e)
			{
				AfxMessageBox(e->ErrorMessage());
			}
			m_nResultCol=m_pRecordset->Fields->GetCount();
			if (!m_pRecordset->ADOEOF)
			{
				m_pRecordset->MoveFirst();
				totalnum=2;
				while(!m_pRecordset->ADOEOF)
				{
					for (loop1=0;loop1<m_nResultCol;loop1++)
					{
						VARIANT varsrc,vardes;
						VariantInit(&varsrc);
						VariantInit(&vardes);
						varsrc=m_pRecordset->GetCollect((long)loop1);
						CString varstr=_T(" ");
						if (varsrc.vt!= VT_NULL)
						{
							if(varsrc.vt!= VT_BSTR)
							{
								VariantChangeType(&vardes,&varsrc, 0, VT_BSTR);
                                varstr=vardes.bstrVal;
							}
							else
							{
                                varstr=varsrc.bstrVal;
                                if (varstr=="")
                                    varstr=" ";
							}
						}
						datalength=varstr.GetLength();
						strcpy(&sendbuf[totalnum],varstr);
						totalnum+=datalength;
						sendbuf[totalnum]=26;
						totalnum++;
					}
					sendbuf[totalnum]=27;
					totalnum++;
					m_pRecordset->MoveNext();
				}
				m_pRecordset->Close();
				sendbuf[0]=totalnum/256;
				sendbuf[1]=totalnum%256;
				while(bufnum1<totalnum)
				{
					bufnum2=3072;
					for (i=0;i<3072;i++)
					{
						if (bufnum1+i==totalnum)
						{
							bufnum2=i;
							break;
						}
						sendbuf2[i]=sendbuf[bufnum1+i];
					}
					send((SOCKET)cs,sendbuf2,bufnum2,0);
					bufnum1+=bufnum2;
				}
			}
			else
			{
				m_pRecordset->Close();
				sendbuf[totalnum]=27;
				totalnum++;
				send(clientSocket,sendbuf,totalnum,0);
			}
		}
		
		if (recvBuf[0]==1)
		{
			recvBuf[0]=32;
			recvBuf[1]=32;
			recvBuf[2]=32;
			sqlstr = _T("");
			sqlstr=recvBuf;
			try
			{
				tp->m_cConn->Execute((_bstr_t)sqlstr,&RecordsAffected,adCmdText);
			}
			catch(_com_error *e)
			{
				AfxMessageBox(e->ErrorMessage());
			}
			sendbuf2[0]='\3';
			send(clientSocket,sendbuf2,1,0);
		}
	}
	ExitThread(0);
	if (m_pRecordset) 
		m_pRecordset.Release();
    m_pRecordset=NULL;
	return 1;
}
UINT AcceptThread(void *s)
{
	int status=0;
	int addrLen=0;
	SOCKADDR_IN clientSockAddr;
	SOCKET serverSocket;
	SOCKET clientSocket;
	addrLen = sizeof (SOCKADDR_IN);
	serverSocket = SOCKET(s);
	while (1)
	{
		CWinThread* pThread;
		clientSocket = accept(serverSocket, (LPSOCKADDR)&clientSockAddr, &addrLen);
		pThread = AfxBeginThread(Clientthread, (LPVOID)clientSocket);
		if (pThread == NULL)
		{
			AfxMessageBox("ERROR: Unable to create thread!", MB_OK);
			status = closesocket(clientSocket);
			if (status == SOCKET_ERROR)
			{
				AfxMessageBox("ERROR: closesocket unsuccessful!", MB_OK);
			}
		}
	}
}
CCTSServerDlg::CCTSServerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCTSServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CCTSServerDlg)
	// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CCTSServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CCTSServerDlg)
	// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CCTSServerDlg, CDialog)
//{{AFX_MSG_MAP(CCTSServerDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_COMMAND(ID_MENUDISPLAY, OnMenudisplay)
ON_COMMAND(ID_MENUQUIT, OnMenuquit)
ON_WM_SIZE()
ON_MESSAGE(WM_SHOWRECEVER,ShowRecever)
ON_WM_CLOSE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CCTSServerDlg message handlers

BOOL CCTSServerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	
	// 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
	
	// TODO: Add extra initialization here
	//////////////////////////////////////////////////////////////////////////
	Init_net(ServerPort);
	//////////////////////////////////////////////////////////////////////////
	
	exitflag=false;
	Noti.cbSize=(DWORD)sizeof(NOTIFYICONDATA);
	Noti.hWnd=this->m_hWnd;
	Noti.uID=IDR_MAINFRAME;
	Noti.uFlags=NIF_ICON|NIF_MESSAGE|NIF_TIP ;
	Noti.uCallbackMessage=WM_SHOWRECEVER;//自定义的消息名称
	Noti.hIcon=m_hIcon;
	strcpy(Noti.szTip,"CTS手持终端应用服务器");//信息提示
	Shell_NotifyIcon(NIM_ADD,&Noti);
    PostMessage(WM_SIZE,0,0);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// 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 CCTSServerDlg::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 CCTSServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

/////////////////////////////////////////////////////////////////////////////
BOOL CCTSServerDlg::Init_net(u_short PORT)
{
	status=WSAStartup(MAKEWORD(1, 1), &Data);
	if (status != 0)
	{
		MessageBox("ERROR: WSAStartup unsuccessful!","handset",MB_OK);
		return  false;
	}
	
	memset(&serverSockAddr, 0, sizeof(serverSockAddr));
    serverSockAddr.sin_port=htons(PORT);
    serverSockAddr.sin_family=AF_INET;
    serverSockAddr.sin_addr.s_addr=htonl(INADDR_ANY);
	
    serverSocket=socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == INVALID_SOCKET)
	{
		MessageBox("socket unsuccessful!","handset",MB_OK);
		status=WSACleanup();
		if (status == SOCKET_ERROR)
			MessageBox("ERROR: WSACleanup unsuccessful!","handset",MB_OK); 
		return false;
	}
	
    status=bind(serverSocket, (LPSOCKADDR) &serverSockAddr, sizeof(serverSockAddr));
    if (status == SOCKET_ERROR)
	{
		MessageBox("ERROR: bind unsuccessful!","handset",MB_OK);
		return false;
	}
	
	status=listen(serverSocket, 5);
	if (status == SOCKET_ERROR)
	{
		MessageBox("ERROR: listen unsuccessful!","handset",MB_OK);
		return false;
	}
	AfxBeginThread(AcceptThread, (LPVOID)serverSocket);
	return true;
}

void CCTSServerDlg::ShowRecever(WPARAM wParam, LPARAM lParam)
{
	if(wParam!=IDR_MAINFRAME)
		return;
	switch(lParam)
	{
	case WM_RBUTTONUP:
		{
			
			LPPOINT lpoint=new tagPOINT;
			::GetCursorPos(lpoint);
			CMenu m_menu2,* m_pop2;
			m_menu2.LoadMenu(IDR_MENU_POP);
			m_pop2= m_menu2.GetSubMenu(0);
            SetForegroundWindow();
			m_pop2->TrackPopupMenu(TPM_LEFTALIGN
				| TPM_RIGHTBUTTON, lpoint->x, 
				lpoint->y,this);
			delete lpoint;
		}
		break;
	case WM_LBUTTONDBLCLK:
		{
            ShowWindow(SW_SHOW);
			ShowWindow(SW_SHOWDEFAULT);
		}
		break;
	}
}

void CCTSServerDlg::OnMenudisplay() 
{
	ShowWindow(SW_SHOW);
	ShowWindow(SW_SHOWDEFAULT);	
}

void CCTSServerDlg::OnMenuquit() 
{
	exitflag=true;
	ExitSystem();
}

void CCTSServerDlg::ExitSystem()
{
	if(MessageBox("您确定要关闭手持终端应用服务器吗?","系统提示!",IDRETRY) == IDNO)
		return ;
	Shell_NotifyIcon(NIM_DELETE, &Noti);
	SendMessage(WM_CLOSE);
}

void CCTSServerDlg::OnSize(UINT nType, int cx, int cy) 
{
	CDialog::OnSize(nType, cx, cy);
	if(cx==0 && cy==0)
		ShowWindow(SW_HIDE);
}

void CCTSServerDlg::OnClose() 
{
	ShowWindow(SW_HIDE);
	if (exitflag)
		CDialog::OnClose();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -