"MFC network programming" study diary 4

1. MFC socket network programming (process example)

 

1. The programming steps of TCP streaming sockets must be linked with library functions before use: Project->Settings->Link->Enter ws2_32.lib, OK!

 

Server-side program:

 

1. Load the socket library

2. Create a socket.

3. Bind the socket to a local address and port (bind).

4. Set the socket to listen mode, ready to receive client requests (listen).

5. Wait for the client request to arrive; when the request arrives, accept the connection request and return a new socket (accept) corresponding to the connection.

6. Use the returned socket to communicate with the client (send/recv).

7. Return and wait for another client request.

8. Close the socket.

 

Client program:

 

1. Load the socket library

2. Create a socket.

3. Send a connection request to the server (connect).

4. Communicate with the server (send/recv).

5. Close the socket.

 

The server-side code is as follows:

 

#include <Winsock2.h>//Add cutting header file

#include <stdio.h>//Load standard input and output header files

void main()

{

WORD wVersionRequested;//version number

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );//1.1 version socket

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) { return; }//Load the socket library, return if the addition fails

if ( LOBYTE( wsaData.wVersion ) != 1 ||HIBYTE( wsaData.wVersion ) != 1 )

{

WSACleanup( );

return;

}//Exit if not 1.1

SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);//Create a socket (socket).

SOCKADDR_IN addrSrv;

addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//Convert Unsigned short to network byte order format addrSrv.sin_family=AF_INET;

addrSrv.sin_port=htons(6000);

bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); //Bind the socket to a local address and port (bind) listen(sockSrv,5);//Set the socket to listen Mode, ready to receive client requests (listen).

SOCKADDR_IN addrClient;//Define address family

int len=sizeof(SOCKADDR);//Initialize this parameter, this parameter must be initialized

while(1)

{

SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len); //The third parameter of accept must have an initial value. //Wait for the client request to arrive; when the request arrives, accept the connection request and return a new socket (accept) corresponding to the connection. //At this point the program is blocked here

char sendBuf[100];

sprintf(sendBuf,"Welcome %s to www.msn.com.cn",inet_ntoa(addrClient.sin_addr)); //Use the returned socket to communicate with the client (send/recv).

send(sockConn,sendBuf,strlen(sendBuf)+1,0);

char recvBuf[100];

recv(sockConn,recvBuf,100,0);

printf("%s\n",recvBuf);

closesocket(sockConn);//Close the socket. Waiting for another user request

}

}

 

 

The client code is as follows:

 

#include <Winsock2.h>

#include <stdio.h>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );//Load socket library

if ( err != 0 ) { return; }

if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1 )

{

WSACleanup( );

return;

}

SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);//Create a socket (socket).

SOCKADDR_IN addrSrv;

addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");

addrSrv.sin_family = AF_INET;

addrSrv.sin_port=htons(6000);

connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));//Send a connection request (connect) to the server.

char recvBuf[100];//Communicate with the server (send/recv).

recv(sockClient,recvBuf,100,0);

printf("%s\n",recvBuf);

send(sockClient,"This is blues_j",strlen("This is blues_j")+1,0);

closesocket(sockClient);//Close the socket.

WSACleanup();//This function must be called to clear the parameters

}

 

 

2. UDP sockets. Server-side (receiver-side) program:

 

1. Create a socket.

2. Bind the socket to a local address and port (bind).

3. Waiting to receive data (recvfrom).

4. Close the socket. Client (sender) program:

1. Create a socket.

2. Send data to the server (sendto).

3. Close the socket.

 

Server side code:

 

#include <Winsock2.h>

#include <stdio.h>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) { return; }

if ( LOBYTE( wsaData.wVersion ) != 1 ||HIBYTE( wsaData.wVersion ) != 1 )

{

WSACleanup( );

return;

}

SOCKET sockSrv = socket (AF_INET, SOCK_DGRAM, 0);

SOCKADDR_IN addrSrv;

addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);

addrSrv.sin_family = AF_INET;

addrSrv.sin_port=htons(6000);

bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));

SOCKADDR_IN addrClient;

int len=sizeof(SOCKADDR);

char recvBuf[100];

recvfrom(sockSrv,recvBuf,100,0,(SOCKADDR*)&addrClient,&len);

printf("%s\n",recvBuf);

closesocket(sockSrv); WSACleanup();

}

 

Client code:

 

#include <Winsock2.h>

#include <stdio.h>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) { return; }

if ( LOBYTE( wsaData.wVersion ) != 1 ||HIBYTE( wsaData.wVersion ) != 1 )

{

WSACleanup( );

return;

}

SOCKET sockClient = socket (AF_INET, SOCK_DGRAM, 0);

SOCKADDR_IN addrSrv;

addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");

addrSrv.sin_family = AF_INET;

addrSrv.sin_port=htons(6000);

sendto(sockClient,"Hello",strlen("Hello")+1,0, (SOCKADDR*)&addrSrv,sizeof(SOCKADDR));

closesocket(sockClient);

WSACleanup();

}

 

3. UDP sockets are commonly used in chat programs. Because TCP's three-way handshake overhead is relatively large.

 

 

2. Summary of some basic operations of MFC, such as operating fonts, menus, pictures, etc.

1: Font operation on the control

method one:

CFont *pfont = m_heightvalue.GetFont();//m_heightvalue is the control

LOGFONT logfont;

pfont->GetLogFont(&logfont);

logfont.lfHeight = 100;

m_font.CreateFontIndirect(&logfont);

m_heightvalue.SetFont(&m_font);

Method Two:

 

CFont m_newFont;

m_newFont.CreatePointFont(250,_T("Official script")); //

m_heightitle.SetFont(&m_newFont);

m_heightitle.SetWindowTextW(strTemp);

 

Two: the operation of the line control:

CBrush newBrush;

CBrush *oldBrush;

CRect rect;

newBrush.CreateSolidBrush(RGB(255,0,0));

CClientDC cClientDc(this);

m_heightitle.GetWindowRect(&rect); //m_heightitle is a graphic control

ScreenToClient(&rect);

oldBrush=cClientDc.SelectObject(&newBrush);

cClientDc.Rectangle(&rect);

cClientDc.SelectObject(oldBrush);

newBrush.DeleteObject();

Three: Change the color of the control:

Added message response: ON_WM_CTLCOLOR()

HBRUSH CDisplayValue::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)

{

HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);

 

switch(pWnd->GetDlgCtrlID())

{

case IDC_STATIC_HEIGHTVALUE:

pDC->SetBkMode(TRANSPARENT);

pDC->SetBkColor(RGB(191,223,255));

pDC->SetTextColor(RGB(255,0,0));

return (HBRUSH)GetStockObject(HOLLOW_BRUSH);

case IDC_STATIC_HEIGHTTITLE:

pDC->SetBkMode(TRANSPARENT);

pDC->SetBkColor(RGB(191,223,255));

pDC->SetTextColor(RGB(0,0,0));

return (HBRUSH)GetStockObject(HOLLOW_BRUSH);

case IDC_STATIC_THICKNESSTITLE:

pDC->SetBkMode(TRANSPARENT);

pDC->SetBkColor(RGB(191,223,255));//SetBkMode(TRANSPARENT);

pDC->SetTextColor(RGB(0,0,0));

return (HBRUSH)GetStockObject(HOLLOW_BRUSH);

case IDC_STATIC_THICKNESSVALUE:

pDC->SetBkMode(TRANSPARENT);

pDC->SetBkColor(RGB(191,223,255));

pDC->SetTextColor(RGB(255,0,0));

return (HBRUSH)GetStockObject(HOLLOW_BRUSH);

default:

break;

}

 

return hbr;

}

 

Four: window size changes:

Add message response void CDebugCrtDlg::OnSize(UINT nType, int cx, int cy)

Parameters: nType specifies the type of resizing required. This parameter can be one of the following values: SIZE_MAXIMIZED

been maximized.

· SIZE_MINIMIZED window has been minimized.

· SIZE_RESTORED The window was resized, but neither SIZE_MINIMIZED nor SIZE_MAXIMIZED apply.

· SIZE_MAXHIDE When other windows are maximized, the message is sent to all popup windows.

· SIZE_MAXSHOW When other windows are restored to their original size, the message is sent to all popup windows.

 

cx specifies the new width of the client area.

cy specifies the new height of the client area.

 

 

Five: Access the txt file

file.Open(m_strFilePath,CFile::modeRead);

char pbufRead[1024];

memset(pbufRead,0, sizeof(pbufRead));

file.SeekToBegin();

file.Read(pbufRead, sizeof(pbufRead));

 

Access the excel file:

http://bbs.csdn.net/topics/390481737

 

Code: E:\c++Code\MMES_New_Code\WarehouseManagementcomV1.62

\WarehouseManagement\Outwarehouse.cpp

 

Six: Icon operation:

After downloading an image from the Internet, it is generally in .jpg format, and the icon format in MFC is .ico format, so it is necessary to convert the .jpg format to .ico format

In general, Baidu online has a direct conversion method of operation. //Generally the width and height are 128*128

 

Seven: Control position change and size change function

 

The size and position of the control can be changed with the functions MoveWindow() or SetWindowPos() of the CWnd class

 

void MoveWindow(int x,int y,int nWidth,int nHeight);

void MoveWindow(LPCRECT lpRect);

The first usage needs to give the new coordinates, width and height of the control;

The second usage gives the CRect object of the storage location;

example:

CWnd *pWnd;

pWnd = GetDlgItem( IDC_EDIT1 ); //Get the control pointer, IDC_EDIT1 is the control ID number

pWnd->MoveWindow( CRect(0,0,100,100) ); //Display an edit control with a width of 100 and a height of 100 in the upper left corner of the window

The SetWindowPos() function is more flexible to use, and is mostly used when only modifying the position of the control without changing the size, or only modifying the size without changing the position:

BOOL SetWindowPos(const CWnd* pWndInsertAfter,int x,int y,int cx,int cy,UINT nFlags);

I will not use the first parameter, generally set to NULL;

x, y control position; cx, cy control width and height;

nFlags commonly used values:

SWP_NOZORDER: ignore the first parameter;

SWP_NOMOVE: ignore x, y, keep the position unchanged;

SWP_NOSIZE: ignore cx, cy, keep the size unchanged;

example:

CWnd *pWnd;

pWnd = GetDlgItem( IDC_BUTTON1 ); //Get the control pointer, IDC_BUTTON1 is the control ID number

pWnd->SetWindowPos( NULL,50,80,0,0,SWP_NOZORDER | SWP_NOSIZE ); //Move the button to the window

(50,80)

pWnd = GetDlgItem( IDC_EDIT1 );

pWnd->SetWindowPos( NULL,0,0,100,80,SWP_NOZORDER | SWP_NOMOVE ); //Set the size of the edit control to

(100,80), position unchanged

pWnd = GetDlgItem( IDC_EDIT1 );

pWnd->SetWindowPos( NULL,0,0,100,80,SWP_NOZORDER ); //The size and position of the edit control are changed

The above method also works for various windows.

 

Eight: convert wchar_t * type to char * type

 

wchar_t is a wide character type, each wchar_t type occupies 2 bytes and is 16 bits wide. The representation of Chinese characters will use wchar_t.

char, as we all know, occupies one byte and is 8 bits wide.

 

CString strName("listen");

char *pcstr = (char *)new char[2 * strName.GetLength()+1] ;

 

WideCharToMultiByte( CP_ACP,

0,

strName, // wchar_t* to convert

-1,

pcstr, // buffer pointer to receive char*

2 * strName.GetLength()+1, // The size of the buffer of pcstr

NULL,

NULL );

 

Wide-byte and multi-byte conversion:

http://www.doc88.com/p-335763678408.html (there is an easy way on this site)

 

Nine: Add menu:

CMenu menu ,* pSubMenu; //Define the cmenu object to be used below

menu.LoadMenu(IDR_MENU1); //Load custom right-click menu

//Get the first popup menu, so the first menu must have submenus

pSubMenu = menu.GetSubMenu(0);

CPoint oPoint; //Define a position used to determine the cursor position

GetCursorPos( &oPoint); //Get the current cursor position so that the menu can follow the cursor

pSubMenu->TrackPopupMenu (TPM_LEFTALIGN, oPoint.x, oPoint.y, this);

 

After adding the menu, you need to respond to the menu: that is, add the command response function corresponding to the menu ID.

 

Ten: Control the scroll bar

wnd is a control or window

wnd.SendMessage(WM_VSCROLL,SB_LINEDOWN)

 

Eleven: word operation:

http://www.jizhuomi.com/software/341.html

Simple operation of word in this link

 

Twelve: file reading

CFile pCfile;

bool bResult=pCfile.Open(lpszPathName,CFile::modeReadWrite);

if (bResult!=FALSE)

{

pCfile.Read(m_str.GetBuffer(pCfile.GetLength()),pCfile.GetLength());

}

pCfile.Close();

 

 

 

3. When the dialog box is minimized and maximized, the corresponding controls will also change.

 

void CLastPackageDlg::OnSysCommand(UINT nID, LPARAM lParam)

{

m_paint=TRUE;

if (nID==SC_MINIMIZE)//When minimized

{

m_paint=FALSE;

}

if ((nID & 0xFFF0) == IDM_ABOUTBOX)

{

CAboutDlg dlgAbout;

dlgAbout.DoModal();

}

else

{

CDialogEx::OnSysCommand(nID, lParam);

}

}

void CLastPackageDlg::OnSize(UINT nType, int cx, int cy)

{

CDialogEx::OnSize(nType, cx, cy);

 

// TODO: add message handler code here

if (m_paint == true)

{

for (int ii= IDC_STATIC_totalcode; ii<= IDC_EDIT_PassWord;ii++)

{

CWnd *pWnd;

pWnd = GetDlgItem(ii);

if(pWnd)

{

CRect rect; //Get the size before the control changes

 

pWnd->GetWindowRect(&rect);

ScreenToClient(&rect);//Convert the size of the control to the area coordinates in the dialog

//cx/m_rect.Width() is the change ratio of the dialog box in the horizontal direction

 

rect.left=rect.left*cx/m_rect.Width();//Resize the control

rect.right=rect.right*cx/m_rect.Width();

rect.top=rect.top*cy/m_rect.Height();

rect.bottom=rect.bottom*cy/m_rect.Height();

pWnd->MoveWindow(rect);//Set the size of the control

}

}

GetClientRect(&m_rect);// Set the changed dialog size to the old size

}

}

 

 

 

 

 

This method improves:

 

void CNerseDlg::OnSize(UINT nType, int cx, int cy)

{

CDialogEx::OnSize(nType, cx, cy);

 

// TODO: add message handler code here

if(nType == SIZE_MINIMIZED)

{

return;

}

 

CWnd *pWnd;

pWnd = GetDlgItem(IDC_LIST_Data_Show); //Which controls need to be changed, get the pointers of which controls

if(pWnd)

{

CRect rect; //Get the size before the control changes

 

pWnd->GetWindowRect(&rect);

ScreenToClient(&rect);//Convert the size of the control to the area coordinates in the dialog

//Compared to the customer service area, the left coordinate point of the rectangle remains unchanged, and the right coordinate point changes.

rect.right=rect.right*cx/m_rect.Width();//cx is the size of the X-axis change

rect.bottom=rect.bottom*cy/m_rect.Height();

pWnd->MoveWindow(rect);//Set the size of the control

 

m_listDataShow.GetClientRect(&rect);

int num = m_listDataShow.GetHeaderCtrl()->GetItemCount();

for (int i = 0; i < num; ++i)

{

m_listDataShow.SetColumnWidth(i,80);

}

 

}

GetClientRect(&m_rect);// Set the changed dialog size to the old size

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325052745&siteId=291194637