"MFC Network Programming" learning Diary 4

Source: Internet
Author: User
Tags htons

One, MFC socket network programming (process example)

Programming steps for 1.TCP streaming sockets you must link library functions before use: Project---Setup->link-> input ws2_32.lib,ok!

Server-side programs:

1. Loading socket font

2. Create socket (socket).

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

4, set the socket to listen mode, ready to receive customer requests (listen).

5, waiting for the customer to request the arrival; When the request arrives, accept the connection request and return a new socket (accept) corresponding to this connection.

6. Communicate with the client using the returned socket (SEND/RECV).

7, return, wait for another customer request.

8. Close the socket.

Client program:

1. Loading socket font

2. Create socket (socket).

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

4, and the server side to communicate (SEND/RECV).

5. Close the socket.

The server-side code is as follows:

#include <winsock2.h>//and cutting head file

#include <stdio.h>//load standard input Output header file

void Main ()

{

WORD wversionrequested;//Version number

Wsadata Wsadata;

int err;

wversionrequested = Makeword (1, 1);//1.1 version of Socket

Err = WSAStartup (wversionrequested, &wsadata);

if (err! = 0) {return;} Loading the socket font, adding the failure to return

if (Lobyte (wsadata.wversion)! = 1 | | Hibyte (wsadata.wversion)! = 1)

{

WSACleanup ();

Return

}//exit if it's not 1.1.

Socket Socksrv=socket (af_inet,sock_stream,0);//create socket (socket).

Sockaddr_in addrsrv;

Addrsrv.sin_addr. S_un. S_addr=htonl (Inaddr_any);//Convert unsigned short to the format of the network byte sequence 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 and prepare to receive client requests (listen).

Sockaddr_in addrclient;//Defining address families

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

while (1)

{

SOCKET sockconn=accept (Socksrv, (sockaddr*) &addrclient,&len); The third argument to accept must have an initial value. Wait for customer request to arrive; When the request arrives, accept the connection request and return a new socket (accept) corresponding to this connection. The program is blocked here at this time

Char sendbuf[100];

sprintf (SendBuf, "Welcome%s to www.msn.com.cn", Inet_ntoa (ADDRCLIENT.SIN_ADDR)); Communicates with the client using the returned socket (SEND/RECV).

Send (Sockconn,sendbuf,strlen (SENDBUF) +1,0);

Char recvbuf[100];

Recv (sockconn,recvbuf,100,0);

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

Closesocket (sockconn);//close socket. Wait for another user to 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 font

if (err! = 0) {return;}

if (Lobyte (wsadata.wversion)! = 1 | | Hibyte (wsadata.wversion)! = 1)

{

WSACleanup ();

Return

}

Socket Sockclient=socket (af_inet,sock_stream,0);//create 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));//Make connection request (connect) to the server.

Char recvbuf[100];//communicates with the server side (SEND/RECV).

Recv (sockclient,recvbuf,100,0);

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

Send (Sockclient, "This was Blues_j", strlen ("This is Blues_j") +1,0);

Closesocket (sockclient);//close socket.

WSACleanup ();//must call this function to clear the parameters

}

Type 2.UDP socket. Server-side (receive-side) programs:

1. Create socket (socket).

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

3, waiting to receive data (RECVFROM).

4. Close the socket. Client (sender-side) Program:

1. Create socket (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. The chat program is commonly used for UDP-socket sockets. Because TCP's three-step handshake overhead is relatively large.

Second, some basic operations of MFC summary, such as the operation of fonts, menus, pictures, etc.

One: Manipulating the font on the control

Method One:

CFont *pfont = M_heightvalue. GetFont ();//m_heightvalue as a 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 row control:

CBrush Newbrush;

CBrush *oldbrush;

CRect rect;

Newbrush.createsolidbrush (RGB (255,0,0));

CClientDC CClientDC (this);

M_heightitle. GetWindowRect (&rect); M_heightitle as a graphical control

ScreenToClient (&rect);

Oldbrush=cclientdc.selectobject (&newbrush);

Cclientdc.rectangle (&rect);

Cclientdc.selectobject (Oldbrush);

Newbrush.deleteobject ();

Three: Change the color of the control:

Add 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)

Parameter: nType Specifies the type of sizing required. This parameter can be one of the following values: • size_maximized window has

is maximized.

· The size_minimized window has been minimized.

· The size_restored window has been changed in size, but neither size_minimized nor size_maximized apply.

· Size_maxhide when other windows are maximized, the message is sent to all pop-up windows.

· Size_maxshow when other windows are restored to their original size, the message is sent to all pop-up windows.

CX Specifies the new width of the customer area.

CY Specifies the new height of the customer area.

V: Access TXT file

File. Open (M_strfilepath,cfile::moderead);

Char pbufread[1024];

memset (pbufread,0, sizeof (Pbufread));

File. Seektobegin ();

File. Read (Pbufread, sizeof (Pbufread));

To access the Excel file:

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

Code: e:\c++code\mmes_new_code\warehousemanagementcomv1.62

\warehousemanagement\outwarehouse.cpp

VI: Operation of the icon:

After downloading images from the web, it is generally in. jpg format, and the icon format in MFC is. ico format, so you need to convert. jpg format to. ico

, General Baidu Online has the operation of direct conversion method. General width and height for 128*128

Seven: Control position change and size change function

The function MoveWindow () or SetWindowPos () of the CWnd class can change the size and position of the control

void MoveWindow (int x,int y,int nwidth,int nheight);

void MoveWindow (Lpcrect lpRect);

The first usage should give the new coordinates and width and height of the control.

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

Cases:

CWnd *pwnd;

PWnd = GetDlgItem (IDC_EDIT1); Gets the control pointer, idc_edit1 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 and is used in situations where the position of the control is changed only if the size is unchanged or only the size is changed:

BOOL SetWindowPos (const cwnd* pwndinsertafter,int x,int y,int cx,int cy,uint nflags);

The first parameter I will not use, generally set to null;

x, y control position, CX, CY control width and height;

Nflags Common values:

Swp_nozorder: ignores the first parameter;

Swp_nomove: Ignore x, Y, maintain position unchanged;

Swp_nosize: Ignore CX, CY, maintain the same size;

Cases:

CWnd *pwnd;

PWnd = GetDlgItem (Idc_button1); Gets the control pointer, idc_button1 the control ID number

Pwnd->setwindowpos (Null,50,80,0,0,swp_nozorder | Swp_nosize); Move the button to the window

(50,80) Office

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 methods also apply to various windows.

Eight: wchar_t * type to char * type

wchar_t are wide character types, each wchar_t type is 2 bytes and 16 bits wide. The expression of Chinese characters will be used to wchar_t.

Char, as we all know, takes up a byte, 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,//Receive char* buffer pointer

2 * strname.getlength () +1,//pcstr buffer size

Null

NULL);

Wide-byte and multi-byte conversions:

Http://www.doc88.com/p-335763678408.html (this site has an easy way)

Nine: Add menu:

CMenu menu, * psubmenu; Define the CMenu object to be used below

Menu. LoadMenu (IDR_MENU1); Loading a custom right-click menu

Gets the first popup menu, so the first menu must have a submenu

Psubmenu = menu. GetSubMenu (0);

CPoint Opoint; Define a location to determine the position of the cursor

GetCursorPos (&opoint); Gets the position of the current cursor so that the menu can follow the cursor

Psubmenu->trackpopupmenu (Tpm_leftalign, Opoint.x, Opoint.y, this);

A response menu is required after the menu is added: that is, the command response function that corresponds to the menu ID is added.

Ten: Control scroll bar

WND for a control or window

Wnd. SendMessage (Wm_vscroll,sb_linedown)

11: Operation of Word:

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

The link simply actions the word

12: Read the file

CFile Pcfile;

BOOL Bresult=pcfile.open (lpszpathname,cfile::modereadwrite);

if (Bresult!=false)

{

Pcfile.read (m_str. GetBuffer (Pcfile.getlength ()), pcfile.getlength ());

}

Pcfile.close ();

When the dialog box is minimized, the corresponding control changes as well.

void Clastpackagedlg::onsyscommand (UINT NID, LPARAM LPARAM)

{

M_paint=true;

if (nid==sc_minimize)//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 of the control before it changes

Pwnd->getwindowrect (&rect);

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

Cx/m_rect. Width () is the ratio of the dialog box to the horizontal change

Rect.left=rect.left*cx/m_rect. Width ();//Resize 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 Control size

}

}

GetClientRect (&m_rect);//Set the changed dialog box 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); What controls you need to change, and what control pointers you get

if (pWnd)

{

CRect rect; Get the size of the control before it changes

Pwnd->getwindowrect (&rect);

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

Relative to the customer service area, the left coordinate point of the rectangle is constant 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 Control size

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 box size to the old size

}

"MFC Network Programming" learning Diary 4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.