Introduction to windows socket programming

Source: Internet
Author: User
Tags htons

Address: http://hi.baidu.com/huangfei564/blog/item/c8fc9c8e62b323fc503d9202.html

 

WinSock programming
For programming using the Winsock API, you should understand the basic knowledge of TCP/IP. Although you can directly use the Winsock API to write network applications, you must have some knowledge about the TCP/IP protocol to write excellent network applications.
1. Relationship between TCP/IP protocol and Winsock network programming interface
Winsock is not a network protocol. It is just a network programming interface. That is to say, it is not a protocol, but it can access many network protocols. You can encapsulate it as some protocols. The current Winsock has basically been implemented and has nothing to do with the protocol. You can use Winsock to call multiple protocols. So what is the relationship between WinSock and TCP/IP? In fact, Winsock is an encapsulation of TCP/IP protocol. You can call various functions of TCP/IP by calling the Winsock interface function. for example, if you want to use the TCP/IP protocol to send data, you can use the Winsock interface function send () to call the data sending function of TCP/IP. As for how to send data, winsock has encapsulated this function for you.
2. Introduction to TCP/IP protocol
The TCP/IP protocol has a wide range of features. It is a layer-4 protocol that includes the definition of various hardware and software requirements. The exact description of TCP/IP protocol should be TCP/UDP/IP protocol. User Data Protocol (UDP) is a message boundary that does not guarantee reliable data transmission. The Transmission Control Protocol (TCP) is a stream transmission protocol. It provides reliable, ordered, bidirectional, and connection-oriented transmission.
Message boundary protection means that the transmission protocol transmits data as an independent message on the Internet, and the receiving end can only receive independent messages. That is to say, there is a message protection boundary. the receiving end can only receive one packet sent by the sending end at a time.
Streaming does not protect the boundaries of message protection. If the sender sends data continuously, the receiver may receive two or more data packets in one receiving action.
For example, if we send three data packets in a row of 2 K, 4 K, and 8 K, the three data packets have already reached the network stack of the receiver, if we use UDP protocol, no matter how large the receiving buffer we use to receive data, we must have three Receiving actions to receive all the packets. With the TCP protocol, we only need to set the buffer size to 14 K or more, so that we can receive all the data packets at a time and only need to receive the data packets at a time.
This is because the UDP Protocol protects the message boundary so that every message is independent. Streaming, however, treats data as a series of data streams and does not regard data as a message. Therefore, when using TCP communication, it is unclear that TCP is stream-based transmission. When sending data continuously, they often know that TCP will lose packets. In fact, when they use a large enough buffer, they may receive two or more packets at a time, and many people tend to ignore this, only the first packet is checked for parsing, but other received data packets are ignored.
3. Simple WinSock programming process
WinSock programming is divided into two parts: the server side and the client side. The general process of the TCP server side is as follows:
For any Winsock-based programming, you must first initialize the Winsock dll library.
Int wsastarup (word wversionrequested, lpwsadata ).
Wversionrequested is the required version of WinSock.
You can call this function to initialize Winsock.
Then you must create a socket ).
Socket socket (int af, int type, int Protocol );
Socket is the core of WinSock communication. All data transmission of WinSock communication is completed through sockets. Sockets contain two types of information: IP address and port, you can determine any communication node in the network.
After the socket () interface function is called to create a socket, you must establish a connection between the socket and the address you need to communicate with. You can bind a function to achieve this connection.
Int BIND (socket S, const struct sockaddr far * Name, int namelen );
Struct sockaddr_in {
Short sin_family;
U_short sin_prot;
Struct in_addr sin_addr;
Char sin_sero [8];
}
It contains the local address to be connected, including the address family, IP address, and port information. The sin_family field must be set to af_inet, which tells WinSock to use the IP address family. Sin_prot is the port number used for communication. Sin_addr is the IP address used for communication.
Here, you must mention the 'big-Endian 'Small Header (little-Endian )'. Because the methods used by different computers to process data are different, intel X86 processors use the 'small head' format to represent multi-byte numbers, that is, to put the low byte in front, the high byte is placed behind, while the Internet standards are the opposite. Therefore, the host bytes must be converted to the network byte order. The Winsock API provides several functions.
Function that converts host bytes into network bytes;
U_long htonl (u_long hostlong );
U_short htons (u_short hostshort );
Function that converts network bytes into host bytes;
U_long ntohl (u_long netlong );
U_short ntohs (u_short netshort );
In this way, when setting IP addresses and port ports, you must convert host bytes into network bytes before using the BIND () function to bind sockets and addresses.
After binding, the server must establish a listener queue to receive client connection requests.
Int listen (socket S, int backlog );
This function can convert the socket to the listening mode.
If the client has a connection request, we must also use
Int accept (socket S, struct sockaddr far * ADDR, int far * addrlen );
To accept client requests.
Now we have basically completed the establishment of a server, and the process for creating a client is to initialize WinSock, then create a Socket socket, and then use
Int connect (socket S, const struct sockaddr far * Name, int namelen );
To connect to the server.
The following is a simple example of creating a server and a client:
Server creation:
Wsadata WSD;
Socket slisten;
Socket sclient;
Udint Port = 800;
Int iaddrsize;
Struct sockaddr_in local, client;
Wsastartup (0x11, & WSD );
Slisten = socket (af_inet, sock_stream, ippoto_ip );
Local. sin_family = af_inet;
Local. sin_addr = htonl (inaddr_any );
Local. sin_port = htons (port );
BIND (slisten, (struct sockaddr *) & Local, sizeof (local ));
Listen (slisten, 5 );
Sclient = accept (slisten, (struct sockaddr *) & client, & iaddrsize );
Client creation:
Wsadata WSD;
Socket sclient;
Udint Port = 800;
Char szip [] = "127.0.0.1 ";
Int iaddrsize;
Struct sockaddr_in server;
Wsastartup (0x11, & WSD );
Sclient = socket (af_inet, sock_stream, ippoto_ip );
Server. sin_family = af_inet;
Server. sin_addr = inet_addr (szip );
Server. sin_port = htons (port );
Connect (sclient, (struct sockaddr *) & server, sizeof (server ));
After a connection is established between the server and the client, both the client and the server can use
Int send (socket S, const char far * Buf, int Len, int flags );
Int Recv (socket S, char far * Buf, int Len, int flags );
Function to receive and send data, because the TCP connection is bidirectional.
When you want to disable the communication link, either party can call
Int Shutdown (socket S, int how );
To disable the specified function of the socket, and then call
Int closesocket (socket S );
To close the socket handle, so that the communication process is complete.
Note: The above Code does not check the function return value. If you are programming on the network, you must check the call results of any Winsock API function. In many cases, the function call may not be successful. In the function described above, if the return value type is int, socket_error will be returned if the function call fails.
4. WinSock programming model
The above is just the simplest Winsock communication method, but in reality many network communications are difficult to solve unexpected situations.
For example, Winsock provides two socket modes: Lock and non-lock. When a socket is locked, many functions are used, such as accpet, send, and Recv. If no data needs to be processed, none of these functions will be returned. That is to say, your application will block the calls to those functions. If you use the non-blocking mode to call these functions, no matter whether data arrives or not, it will return. Therefore, in non-blocking mode, most of the calls to these functions will return failures, so we need to handle many unexpected errors.
This is clearly not what we want to see. We can use the Winsock communication model to avoid these situations.
Winsock provides five socket I/O models to solve these problems. They are select, wsaasyncselect, wsaeventselect, overlapped, and completion port ).
Here we will introduce the select and wsaasyncselect models in detail.
The select model is the most common I/O model. Use
Int select (INT NFDs, fd_set far * readfds, fd_set far * writefds, fd_set far * limit TFDs, const struct timeval far * timeout );
Function to check whether the Socket socket you want to call has data to be processed.
Select contains three socket queues, which represent the following:
Readfds, check readability, writefds, check writability, limit TFDs, and exceptional data.
Timeout is the return time of the select function.
For example, to check whether a socket has data to receive, we can add the socket handle to the readability check queue and then call select. If the socket has no data to receive, the select function will delete the socket from the readability check queue. Therefore, we only need to check whether the socket handle is still in the readability queue, so we can know whether there is any data to be received.
Winsock provides some macros used to operate the socket queue fd_set.
Fd_clr (S, * Set) deletes the handle s from the queue set.
Fd_isset (S, * Set) checks whether the handle s exists in the queue set.
Fd_set (S, * Set) adds the handle s to the queue set.
Fd_zero (* Set) initializes the set queue to an empty queue.
Wsaasyncselect (asynchronous selection) Model: The wsaasyncselect model establishes a connection between a window and a socket handle. When a Socket network event occurs, a message is sent to the window, then, you can process data receiving and sending in the message response function of the window.
Int wsaasyncselect (socket S, hwnd, unsigned int wmsg, long Levent );
This function can establish a connection between the socket handle and the window,
Wmsg is a custom message.
Levent is a network event. Including fd_read, fd_write, fd_accept, fd_connect, and fd_close. Several events.
For example, you need to receive network events of fd_read, fd_write, and fd_close. Yes
Wsaasyncselect (S, hwnd, wm_socket, fd_read | fd_write | fd_close );
In this way, when there are fd_read, fd_write or fd_close network events, the Windows hwnd will receive the wm_socket message. The lparam of the Message Parameter indicates what the event occurs, and the csocket class of MFC, this model is used.

Related Article

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.