[Recommended] Windows Network Programming Classic Getting Started

zhaozj2021-02-16  46

[Recommended] Windows Network Programming Classic Getting Started

Caiyi9000 original

For a Windows network programming beginner, the following method is a classic entry. Beginners recommends not to use the class provided by the MFC, and use the Windows API to make a simple server and client, which helps to understand the Socket programming mechanism. For the sake of simplicity, the application is a MFC-based standard dialog. Winsock implements Windows API: (1) The server side has two threads: main thread - you need to write the following functions to implement

#define network_event user_message 100 file: // Define network events

SockAddr_in clientaddr; file: // Temporarily store client IP address

File: // Define the message mapping function to map the network event defined above to the process function.

File: // OnNETEVENT is the network event handler, it defines below

ON_MESSAGE (NetWork_Event, OnNetEvent);

Call the subunies of the following initialization network in the initialization function in your dialog

BOOL INITNETWORK () File: // Initialization Network

{

File: // Initialize the TCP protocol

Bool Ret = WSAStartup (Makeword (2, 2), & WSADATA);

IF (ret! = 0)

{

MessageBox ("Initialization Socket Failed!");

Return False;

}

File: // Create server-side socket

Socket Serversocket

= Socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);

IF (Serversocket == Invalid_socket)

{

MessageBox ("Create a socket failed!");

CloseSocket (M_Socket);

WSACLEANUP ();

Return False;

}

File: // Bind to a local port

SockAddr_in Localaddr;

Localaddr.sin_family = af_INet;

Localaddr.sin_Port = HTONS (1688);

Localaddr.sin_addr.s_addr = 0;

IF (Bind (Const struct socketdr *) & localaddr,

SIZEOF (SOCKADDR) == Socket_ERROR)

{

MessageBox ("Binding Address Failed!");

CloseSocket (M_Socket);

WSACLEANUP ();

Return False;

}

File: // Register the network asynchronous event, m_hwnd is the handle of the application's master dialog or the main window

WSaasyncselect (Serversocket, M_HWnd, Network_Event,

FD_ACCEPT | FD_CLOSE | FD_READ | FD_WRITE);

Listen (Serversocket, 5); file: // Sets the listening mode

Return True;

}

FILE: / / Define the response function of network events

Void OnNetEvent (WPARAM WPARAM, LPARAM LPARAM)

{

File: // Call the API function to get the network event type

Int Ievent = WsagetSelectEvent (LPARAM);

File: // Get the client sleeve of this event

Socket psock = (socket) wparam;

Switch (IEvent)

{

Case FD_ACCEPT: File: // Client Connection Request

{

ONACCEPT ();

Break;

}

Case FD_Close: file: // Client breaks the event: {

OnClose (PSock);

Break;

}

Case FD_Read: file: // Network Packet Arrival Event

{

OnRecEive (PSock);

Break;

}

Case FD_WRITE: File: / / Send network data event

{

Onsend (PSock);

Break;

}

DEFAULT: BREAK;

}

}

Void onaccept (SOCET PSOCK) File: / / Respond to the client connection request function

{

INT LEN = SizeOf (SockAddr);

File: // Call the API function, accept the connection, and return a new socket

File: / / You can also get the client's IP address

Socket Clientsocket = Accept (ServerSocket,

Struct SockAddr *) & ClientAddr, & len;

File: // Register for the new socket, pay attention to the Accept event

IF (Wsaasyncselect (ClientSocket, M_HWnd, IP_Event,

FD_CLOSE | fd_read | fd_write) == Socket_ERROR)

{

MessageBox ("Registered Asynchronous Event Failed!");

Return;

}

File: // Self-editing function, save this client's related information: socket,

// IP address, login time

SaveClientSocket (ClientSocket, ClientTimer);

}

Void OnClose (Socet PSock)

{

File: // Self-editing function, end communication with the corresponding client, release the corresponding resources and do corresponding processing

EndClientSocket (PSOCK);

}

Void Onsend (Socet PSock)

{

File: // Self-editing function, do some prerequisites when sending data to the client

Handleonsend (PSock);

}

Void OnRecEive (Socet Psock)

{

Recv (...); file: // Call the API function, read the packets in the network buffer

File: // Self-editing function, send this packet and send this data client

File: // ClientSocket package into a network message

Buildnetmsg (...);

File: // Self-editing function, put this network message into a message queue, deal with the working thread

Savenetmsg (...);

SetEvent (...); file: // Trigger a work thread with event object

}

After the client logs in, the computer name will be sent to the server. After the server is connected, save it. This allows the server to display all online client information, including: client computer name, IP address, login time, etc. Note: The client does not have an onaccept () function, but there is an onconnect () function. Work Thread - Create and start a work thread when you initialize your application

AfxBeginthread (Workthread, this, thread_priority_normal);

File: // This may be the handle of the application's primary dialog or main window

Uint Workthread (LPVOID PPARAM)

{

While (1)

{

File: // Waiting for multiple events arrival

int RET = WaitFormultiPleObject (...);

Switch (re)

{

Case Object_0:

{

If (bnewnetmsg) file: / / View the network message queue has new web messages

{

ReadNetmsg (...); file: // reads out if there is a new network message

Handlenetmsg (...); file: // Handling this web message

}

Break;

}

Case Object_0 1:

{

File: // Doing an exit process

Break;

}

DEFAULT: BREAK;

}

Return 0;

}

When the client is single-thread, when the server is logged to the server, use the connection () function to send a request for the server; the client does not have an onaccept () function, but there is an onconnect () function. Preproreating during the onConnect () function; responds to the onRecEive () function and processes network data; in the onclose () function responds to the closing event of the server; when you do data in the onsend () function Prerequisites; if you want to realize online communication between the clients (ie, the so-called chat room), you can also make a multi-point to multi-point local area network multicast model model based on the UDP protocol. Talk to you, you first implement the above procedure. The above I / O asynchronous model is based on Windows-based message mechanism, and you can also use event models, overlapping models, or complete port models. It is recommended that you refer to the books such as the Windows Network Programming Guide. If you can be skilled on the above mechanism, you have already understood the mechanism of Winsock's online program, next you can make more exciting programming, not only can transfer normal data online, but also transmit voice, video data You can also do a chat room yourself, and you can share your results in the LAN in the laboratory.

转载请注明原文地址:https://www.9cbs.com/read-21904.html

New Post(0)