How to Use CSocket and winsocket (key knowledge of network communication)

Source: Internet
Author: User

Socket usage steps

1. Start Winsock: Initialize Winsock DLL, negotiate with Winsock versions to support and assign necessary
Resources. (Server and client)

Int WSAStartup (WORD wVersionRequested, LPWSADATA lpWSAData) wVersionRequested is used to load the Winsock version. Generally, the following settings are used: wVersionRequested = MAKEWORD () or directly assigned values: wVersionRequested = 2LPWSADATA is the version information loaded after the Socket is initialized. It is defined as follows: typedef struct WSAData {WORD wVersion; WORD wHighVersion; char szDescription [WSADESCRIPTION_LEN + 1]; char szSystemStatus [WSASYS_STATUS_LEN + 1]; unsigned short iMaxSockets; unsigned short iMaxUdpDg; char FAR * lpVendorInfo;} WSADATA, FAR * LPWSADATA;

If the data after successful loading is:

WVersion = 2 indicates that the loaded version is 2.0. WHighVersion = 514 indicates that the maximum socket version supported by the current system is 2.2. SzDescription = "WinSock 2.0" szSystemStatus = "Running" indicates that the instance is Running. IMaxSockets = 0 indicates the maximum number of sockets opened at the same time. 0 indicates no limit. IMaxUdpDg = 0 indicates the maximum number of opened data packets at the same time. 0 indicates no limit. LpVendorInfo is not used and is reserved for vendor-specified information.

How to use this function:

WORD wVersion = MAKEWORD (2, 0); WSADATA wsData; int nResult = WSAStartup (wVersion, & wsData); if (nResult! = 0) {// error handling}

2. Create a socket: (server and client)

SOCKET socket (int af, int type, int protocol); af is the network address type, generally AF_INET, indicating to be used in the Internet domain. Type is the socket type, which has been described earlier. Protocol is the specified network protocol, generally IPPROTO_IP.

Usage:

SOCKET sock = socket (AF_INET, SOCK_STREAM, IPPROTO_IP); if (sock = INVALID_SOCKET) {// error handling}

3. Socket binding: bind the local address to the created socket. (Server and client)

Int bind (SOCKET s, const struct sockaddr FAR * name, int namelen) s is the created SOCKET. The name is the socket address structure and the sockaddr structure. As discussed above, we generally use the sockaddr_in structure and forcibly convert it to the sockaddr structure. Namelen is the length of the address structure.

Usage:

Sockaddr_in addr; addr. sin_family = AF_INET; addr. sin_port = htons (0); // ensure the byte sequence addr. sin_addr.s_addr = inet_addr ("192.1.8.84") int nResult = bind (s, (sockaddr *) & addr, sizeof (sockaddr); if (nResult = SOCKET_ERROR) {// handle errors}

4. Socket listening: (server)

int listen(SOCKET s, int backlog )

S is a bound but not connected socket.
Backlog specifies the maximum queue length waiting for connection. this parameter is very important because the server can
To provide multiple connections.
Usage:

Int nResult = listen (s, 5) // up to 5 connections if (nResult = SOCKET_ERROR) {// error handling}

5. Socket waiting for connection: (server side)

SOCKET accept( SOCKET s, struct sockaddr FAR * addr, int FAR * addrlen )

S is the socket in listening mode.
Sockaddr is the network address of the client returned after receiving the message.
Addrlen is the length of the network address.

Usage:

Sockaddr_in addr; SOCKET s_d = accept (s, (sockaddr *) & addr, sizeof (sockaddr); if (s = INVALID_SOCKET) {// error handling}

6. Socket Connection: link two sockets to prepare for communication. (Client)

int connect(SOCKET s, const struct sockaddr FAR * name, int namelen )

S is the socket that you want to connect.
Name is the socket address to connect.
Namelen is the length of the socket address structure.

Usage:

Sockaddr_in addr; addr. sin_family = AF_INET; addr. sin_port = htons (0); // ensure the byte sequence addr. sin_addr.s_addr = htonl (INADDR_ANY) // guarantee the byte sequence int nResult = connect (s, (sockaddr *) & addr, sizeof (sockaddr); if (nResult = SOCKET_ERROR) {// handle errors}

7. Send data through a socket: (server and client)

int send(SOCKET s, const char FAR * buf, int len, int flags )

S is the socket for server listening.
Buf is the pointer to the data buffer to be sent.
Len is the length of the sending data buffer.
Flags indicates the data sending flag.
The returned value is the number of characters that send data.

◆ Here we will talk about this sending mark. The receiving mark discussed in the following 8 is also the same:

The flag value must be 0 or a combination defined as follows: 0 indicates no special behavior.

# Define MSG_OOB 0x1/* process out-of-band data */
# Define MSG_PEEK 0x2/* peek at incoming message */
# Define MSG_DONTROUTE 0x4/* send without using routing tables */
MSG_OOB indicates that data should be sent out of band. The so-called out-of-band data is TCP emergency data.
MSG_PEEK indicates that useful data is copied to the buffer but not deleted from the system buffer.
MSG_DONTROUTE: Do not Route packets out.

Usage:

Char buf [] = "xiaojin"; int nResult = send (s, buf, strlen (buf); if (nResult = SOCKET_ERROR) {// error handling}

8. Socket data reception: (client)

int recv( SOCKET s, char FAR * buf, int len, int flags )

S is the socket for preparing to receive data.
Buf is the buffer for preparing to receive data.
Len is the size of the buffer for preparing to receive data.
Flags indicates the data receiving mark.
The returned value is the number of characters in the received data.

Usage:

Char mess [1000]; int nResult = recv (s, mess,); if (nResult = SOCKET_ERROR) {// error handling}

9. Interrupt socket connection: notifies the server or client to stop receiving and sending data. (Server and client)

int shutdown(SOCKET s, int how)

S is the socket to interrupt the connection.
How indicates which operations are prohibited. The values are SD_RECEIVE, SD_SEND, and SD_BOTH.

#define SD_RECEIVE 0x00#define SD_SEND 0x01#define SD_BOTH 0x02

Usage:

Int nResult = shutdown (s, SD_BOTH); if (nResult = SOCKET_ERROR) {// error handling}

10. Close the socket: Release the occupied resources. (Server and client)

int closesocket( SOCKET s )

S is the socket to be closed.

Usage:

Int nResult = closesocket (s); if (nResult = SOCKET_ERROR) {// error handling}

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.