Recently saw the "window program design" feeling in the network is good, speak very easy to understand, with everyone to communicate
Reprint Please specify source: http://blog.csdn.net/u010484477 Thank you ^_^
The general steps for using Winsock programming are relatively fixed.
1. Mount, initialize, and release of the Winsock library
All WinSock functions are exported from the Ws2_32.dll Library, VC + + is not connected to the library by default, and if you want to use the Winsock API, you must include the corresponding library file.
#pragma commment (lib, "Wsock32.lib")
WSAStartup must be the Winsock function that the application calls first. It allows the application to specify the version of the required Windows Sockets API to obtain the details of a particular Winsock implementation. The application can invoke other Winsock APIs only after the function has been successfully executed.
int WSAStartup (
WORD wversionrequested,//application supports the highest Winsock library version. The high byte is the minor version number, and the low byte is the primary version number
Lpwsadata lpwsadata//A pointer to the WSADATA structure. It is used to return the details of the DLL library
);
The lpwsadata parameter is used to obtain the details of the DLL library, as defined in the following structure.
typedef struct WSADATA {
WORD wversion; //library file recommended version used by application
The highest version supported by the WORD whighversion;//library file
Char szdescription[wsadescription_len+1]; Library description string
Char szsystemstatus[wsasys_status_len+1]; System Status String
Unsigned short imaxsockets;//The maximum number of nested node words supported at the same time
Unsigned short imaxudpdg;//obsolete parameters in version 2.0
char FAR * LPVENDORINFO; deprecated parameters in version 2.0
} wsadata, FAR * lpwsadata;
The function call returned successfully to 0. Otherwise, call the WSAGetLastError function to see the cause of the error. This function is equivalent to the Win32 API GetLastError, which takes the code that made the last error.
Each call to WSAStartup must correspond to a call to WSACleanup , which frees the Winsock library.
int wsacleanup (void);
2. Create and close a set of section words
Before you use a nested word, you must call the socket function to create a nested section object , and the function call will return the socket handle successfully.
Socket Socket (
The int af,//is used to specify the address format used for the nested section, and only af_inet is supported in Winsock
int type,//is used to specify the type of the nested section Word
The int protocol//is used with the type parameter to specify the protocol type to use. It could be ipproto_tcp, etc.
);
The type parameter is used to specify the types of the nested section words. The section Word has the flow sleeve Word, the Data report sleeve word and the original stanza word and so on,
Here are a few common types of section definitions:
Sock_stream , using the TCP protocol to provide reliable transmission with a connection
Sock_dgram Datagram socket word, using UDP protocol to provide non-connected unreliable transmission
Sock_raw The original nesting word, the WinSock interface does not use a specific protocol to encapsulate it, but instead processes the datagram itself and the protocol header
When the type parameter is specified as Sock_stream and SOCK_DGRAM, the system has been explicitly determined to work with the TCP and UDP protocols, so the protocol parameter can be specified as 0.
The function execution fails to return Invalid_socket (that is,-1), and you can get the error code by calling WSAGetLastError.
When you do not use the socket created by the socket, you should call the closesocket function to close it. If no error occurs, the function returns 0, otherwise returns SOCKET_ERROR.
The closesocket function uses the following.
int closesocket (SOCKET s); The only argument to the function is the handle of the section word to be closed.
3. Bind a nested word to a specified IP address and port number
The function that associates a local address for a section word is bind, using the following usage.
int bind (
Socket s,//Socket HANDLE
const struct SOCKADDR* name,//The local address to associate
The length of the int namelen//address
);
The BIND function is used on a nested section word that does not have a connection, and it is intended to bind a connection-oriented or non-connected set of nodes. When a section word is created by the socket function, he exists in the specified address family, but it is unnamed. The BIND function establishes a local association of this socket by arranging a local name to an unnamed socket.
The local name consists of 3 parts: host address , protocol number (UDP or TCP, respectively) , and port number .
filling the SOCKADDR_IN structure
Sockaddr_in sin;
sin.sin_family = af_inet;
Sin.sin_port = htons (8888);
Sin.sin_addr. S_un. S_ADDR = Inaddr_any;
bind this section Word to a local address
if (:: Bind (S, (lpsockaddr) &sin, sizeof (sin)) = = Socket_error)
{
printf ("Failed bind () \ n");
:: WSACleanup ();
return 0;
}
The sin_familly field in the SOCKADDR_IN structure is used to specify the address family , which has the same meaning as the AF parameter in the socket function, so the only value that can be used is af_inet.
The sin_port field and the sin_addr field specify the port number and IP address to which the section word needs to be bound, respectively. The byte order of the data placed in both fields must be the network byte order .
Because the network byte order is exactly the opposite of the Intel CPU's byte order, you must first convert with the Htons function. If the application does not care about the address used, you can specify Inaddr_any for the Internet address and 0 for the port number. If the Internet address equals inaddr_any, the system automatically uses all IP addresses configured by the current host, which simplifies programming, and if the port number equals 0, the system assigns a unique port number to the application when the program executes, with values between 1024 and 5000. The application can use getsockname after bind to know the address assigned to it. Note, however, that it is not possible to fill in the Internet address until the getsockname is connected, because multiple addresses may be available for a host.
4. Set the section word into the listening state
The Listen function sets the section word into the listening state.
int Listen (
Socket s,//Socket HANDLE
int backlog//The maximum number of outstanding connections that are allowed to remain in the listener queue
);
To accept the connection, first use thesThe ocket function creates a set of section words, and then useThe bind function binds it to a local address, and then useThe Listen function specifies a backlog for the incoming connection, and finally useaccept the requested connection。 The listen is only applied on a nested section word that supports connections, such as the Sock_stream type. After the function has been successfully executed, the nested word s enters passive mode, and the incoming connection is notified and queued for processing. Servers that process multiple connection requests at the same time typically use the Listen function: If a connection request arrives and the queue is full, the client receives a WSAECONNREFUSED error.
5. Accept connection Requests
The Accept function is used for accepting incoming connections.
SOCKET Accept (
Socket s,//Socket HANDLE
struct sockaddr* addr,//A pointer to the SOCKADDR_IN structure to obtain the address information of the other party
int* addrlen//is a pointer to the length of the address
);
The function is on the sRemove UnhandledIn the connectionFirst Connection, and then create one for this connectionnew set of section words, return it's Handle。 The newly created section Word is a nested word that handles the actual connection, and it has the same properties as S.
The program works by default in blocking mode, in which case the accept function waits until a new connection occurs to return if no unresolved connection exists.
Addrlenparameter is used to specify the size of the space referred to by addr, and also to returnAddressOfactual length。 If addr or Addrlen is NULL, no information about the remote address is returned. After the client program creates the nested word, it uses the Connect function to request a connection to the server, and the function prototype is as follows.
int Connect (
Socket s,//Socket HANDLE
const struct SOCKADDR FAR * name,//A pointer to the SOCKADDR_IN structure that contains the address information of the server to which you want to connect.
int namelen//length of sockaddr_in structure
);
The first parameter, s, is the client-side section word used by this connection. The other two parameters name and Namelen are used to address the remote section Word (the server that is listening on).
6. Send and receive data
In the case of convection, the send and recv functions are generally used to send and receive data.
int Send (
Socket s,//Socket HANDLE
const char FAR * buf,//the buffer address to send data to
int len,//buffer length
The int flags//Specifies the invocation method, which is usually set to bit 0
);
int recv (SOCKET s, char FAR * buf, int len, int);
The Send function sends the data in the buffer on a connected set of nodes, returning the actual number of bytes of data sent.
The recv function receives a number of data from the other, and stores it to the specified buffer . The flags parameter is typically set to 0 in both functions.
In blocking mode, send will block the execution of the thread until all the data is sent (or an error occurs).
The RECV function returns as much of the currently available information as it can to the size specified by the buffer.
The process for creating a server program and a client program:
Finally, I would like to send you a word I love:
You have to use your efforts in exchange for success, then success will be like a slap in the face of those who once looked down on you