Winsock Network Programming Fundamentals (2) client

Source: Internet
Author: User

Now let's talk about how to create a TCP/IP model-based client and server with Winsock.

TCP can provide reliable data transfer between two computers, and when the application uses TCP communication, a virtual connection is established between the two computers, and the computer can be exchanged for two-way byte streams after the connection.

The following is a simple client implementation that sends data.

Creating a client connection is simple:

1. Create a socket, define the Addrinfo object, and initialize the values (the object contains a SOCKADDR structure)
struct addrinfo *result = NULL,                *ptr = NULL,                hints;ZeroMemory( &hints, sizeof(hints) );hints.ai_family = AF_UNSPEC;  //可以是IPv4或IPv6地址hints.ai_socktype = SOCK_STREAM;hints.ai_protocol = IPPROTO_TCP;

Call the Getaddrinfo function to determine the server IP address (passed by command-line arguments) and port

#define DEFAULT_PORT "27015"// Resolve the server address and portiResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);if (iResult != 0) {    printf("getaddrinfo failed: %d\n", iResult);    WSACleanup();    return 1;}

Socket prototype:

Socket

in int AF,//protocol address family, using IPV4 to describe Winsock, set to Af_inet

in int type,//socket type, TCP/IP set to SOCK_STREAM,UDP/IP set to Sock_dgram

in int protocol//For delivery qualification with multiple ingress for a given address family and type, TCP set to IPPROTO_TCP,UDP set to IPPROTO_UDP

);

Call socket to create nested words, error detection

SOCKET ConnectSocket = INVALID_SOCKET;ptr=result;ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,     ptr->ai_protocol);if (ConnectSocket == INVALID_SOCKET) {    printf("Error at socket(): %ld\n", WSAGetLastError());    freeaddrinfo(result);    WSACleanup();    return 1;}
2. The name of the server to which you are connected. (in TCP/IP, it is the IP address and port number of the listener server)
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);if (iResult == SOCKET_ERROR) {    closesocket(ConnectSocket);    ConnectSocket = INVALID_SOCKET;}//释放资源freeaddrinfo(result);if (ConnectSocket == INVALID_SOCKET) {    printf("Unable to connect to server!\n");    WSACleanup();    return 1;}

Client after creating the nested word, the program uses the Connect function to request the Server Connect,Connect prototype:

int Wsaapi Connect (

In socket s,//to establish a connected socket

In const struct SOCKADDR FAR * name,//point to save the address structure to establish the connection information

in int namelen//parameter 2 points to the size of the address structure

);

3. Send and receive data.

send and receive data is the subject of network programming, data can be used on sockets that have already been connected to send or WSASend (WINSOCK2) , accept available recv and WSARecv. Sending and receiving data is a char type (byte-oriented data).

#define DEFAULT_BUFLEN 512int recvbuflen = DEFAULT_BUFLEN;char *sendbuf = "this is a test";char recvbuf[DEFAULT_BUFLEN];int iResult;iResult = send(ConnectSocket, sendbuf, (int) strlen(sendbuf), 0);if (iResult == SOCKET_ERROR) {    printf("send failed: %d\n", WSAGetLastError());    closesocket(ConnectSocket);    WSACleanup();    return 1;}printf("Bytes Sent: %ld\n", iResult);iResult = shutdown(ConnectSocket, SD_SEND);if (iResult == SOCKET_ERROR) {    printf("shutdown failed: %d\n", WSAGetLastError());    closesocket(ConnectSocket);    WSACleanup();    return 1;}do {    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);    if (iResult > 0)        printf("Bytes received: %d\n", iResult);    else if (iResult == 0)        printf("Connection closed\n");    else        printf("recv failed: %d\n", WSAGetLastError());} while (iResult > 0);

All the error codes returned by the send and receive data are SOCKET_ERROR, and the system calls WSAGetLastError () for detailed error information once an error is returned.

Common errors:


Wsaeconnaborted and Wsaeconnreset: Connection is shutting down (timed out or the connection is being closed due to communication put)
Wsaewouldblock: Socket is in non-blocking mode or asynchronous state.


Use the Send and recv function prototypes.

int Send (

Socket s,//section handle

const char far* buf,//The address of the buffer to send the data to

int len,//Length of buffer

int flags//specified invocation method, usually set to 0

);

int recv (

SOCKET S,

Char far* buf,

int Len,

int flags

);

The Send function sends the data in the buffer on a connected set of nodes, returns the actual number of bytes sent, the RECV function receives the data from the other, and stores it to the specified buffer. The flag parameter is typically set to 0 in both functions.

In blocking mode, send will block the execution of the thread until all the data has been sent (or an error occurs), and the Recv function will return as much current information as possible to the size specified by the buffer.

function execution failed to return Invalid_socket (-1), the Closesocket function should be called to close it. If no error occurs, the function returns 0, otherwise returns SOCKET_ERROR. The function uses the following:

int Closesocket (

__IN socket S//function only parameter is the handle of the section word to be closed

);

4. Disconnect, close the socket (when the client has emitted data, you can use the Shutdown function and the Sd_send macro to turn off the send socket, the client still allows the data from the server socket to be accepted)
iResult = shutdown(ConnectSocket, SD_SEND);if (iResult == SOCKET_ERROR) {    printf("shutdown failed: %d\n", WSAGetLastError());    closesocket(ConnectSocket);    WSACleanup();    return 1;}closesocket(ConnectSocket);WSACleanup();

Complete client code is included:

#ifndef win32_lean_and_mean#define win32_lean_and_mean#endif#include <windows.h> #include <winsock2.h># Include <WS2tcpip.h> #include <IPHlpApi.h> #include <stdio.h> #pragma comment (lib, "Ws2_32.lib") # pragma comment (lib, "Mswsock.lib") #pragma comment (lib, "Advapi32.lib") #define Default_port "27015" #define Default_ Buflen 512int Main (int argc, char* argv[]) {wsadata wsadata;int iresult;struct addrinfo *result = NULL, *ptr = null,hints;c Har *sendbuf = "This is a test"; char recvbuf[default_buflen];int recvbuflen = Default_buflen; SOCKET Connectsocket = invalid_socket;if (argc! = 2) {printf ("Usage:%s server-name\n", argv[0]);} Initialize Winsockiresult = WSAStartup (Makeword (2, 2), &wsadata), if (Iresult! = 0) {printf ("WSAStartup failed:%d\n", Iresu LT); return 1;} ZeroMemory (&hints, sizeof (hints)); hints.ai_family = Af_unspec;hints.ai_socktype = Sock_stream;hints.ai_protocol = ipproto_tcp;//determine the server address and port Iresult = getaddrinfo (argv[1], Default_port, &hints, &result);if (Iresult! = 0) {printf ("Getaddrinfo failed:%d\n", Iresult); WSACleanup (); return 1;} Try to connect to the server address until success for (ptr = result; ptr = NULL; ptr = ptr->ai_next) {//create socket to connect to server Connectsocket = socket (ptr->ai_f amily, Ptr->ai_socktype, Ptr->ai_protocol); if (Connectsocket = = Invalid_socket) {printf ("Error at SOCKET ():%ld\n ", WSAGetLastError ()); Freeaddrinfo (result); WSACleanup (); return 1;} Connect Server Iresult = Connect (Connectsocket, ptr->ai_addr, (int) ptr->ai_addrlen), if (Iresult = = Socket_error) { Closesocket (Connectsocket); Connectsocket = invalid_socket;continue;} break;} Release resource Freeaddrinfo (Result), if (Connectsocket = = Invalid_socket) {printf ("Unable to connect to server!\n"); WSACleanup (); return 1;} Send SendBuf content iresult = Send (Connectsocket, sendbuf, (int) strlen (sendbuf) + 1, 0); if (Iresult = = socket_error) {printf ("se nd failed:%d\n ", WSAGetLastError ()); closesocket (Connectsocket); WSACleanup (); return 1;} printf ("Byte send:%ld\n", iresult);//Disconnect after data send is complete Iresult = Shutdown (connectsocket, SD_send); if (Iresult = = socket_error) {printf ("Shutdown faild:%d\n", WSAGetLastError ()); closesocket (Connectsocket); WSACleanup (); return 1;} Closes the connection after receiving the response do {Iresult = recv (Connectsocket, Recvbuf, Recvbuflen, 0); if (Iresult > 0) printf ("Byte Received:%d\n", IR Esult); else if (Iresult = = 0) printf ("Connection closed\n"); elseprintf ("Recv failed:%d\n", WSACleanup ());} while (Iresult > 0);//Clear Socket closesocket (connectsocket);    WSACleanup (); return 0;}

This article link: HTTP://WWW.BUGCODING.COM/ENTRY/10

Winsock Network Programming Fundamentals (2) client

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.