Use Winsock client program

Source: Internet
Author: User

I don't know whether this program has any value. I learned WinSock programming first.

Before the official start, introduce the client/server programs. Many network programs use the client/server model (C/S model. In fact, we are very familiar with this architecture. The relationship between browsers and web servers is the relationship between C/S. Data Interaction between well-known servers and clients is performed according to certain standards. The TCP/IP architecture belongs to the application layer protocol. Compared with well-known C/S applications, our self-developed C/S applications use private application protocols rather than public standards (of course, you can also use well-known protocols ). With this understanding, let's take a look at the key points of the Network C/S program.

1 connection-oriented and connectionless

The data communication between the server and the client is provided by the underlying computer network communication protocol TCP/IP. the TCP/IP protocol family provides two transport layer services for the application layer service: connection-oriented TCP protocol and connectionless UDP protocol. Therefore, when developing your own C/S system, you must first decide whether to select a connection-oriented or connectionless transmission protocol.

The difference between TCP and UDP is obvious: UDP is a very simple transport layer protocol, which cannot guarantee that the data will eventually arrive at the destination; in contrast, TCP provides reliable transmission services, validation, timeout and retransmission mechanisms ensure that application layer data is reliably transmitted to the destination, and TCP also provides traffic control.

Using UDP or using TCP does not have certain standards. Generally, UDP is used only in the following situations:

(1) Data Interaction between C/S is very simple, such as standard services daytime and echo.

(2) Compared with data loss, the system cannot tolerate the time consumed by timeout retransmission. A typical application is an audio/video system.

(3) The system architecture requires multicast or broadcast packets.

In addition, if you want to use UDP in the system, you must design an application-layer protocol that ensures reliable data transmission: To achieve this goal, confirm, timeout retransmission and traffic control may be necessary, which is provided by the TCP protocol.

2 concurrency and iteration

Generally, a server needs to provide services to multiple customers at the same time, while a client usually only contacts one server (a common exception is a Web browser ). We call a server that can receive connections from multiple clients as a concurrent server, and an iterative server that can only serve one customer at a time ).

Iterative servers are usually used to provide some simple services, such as daytime and echo. For the provision of complex services, it is not advisable to stop on the service of a customer for a long time and reject other customers.

With the above knowledge, we develop a client program for analysis:

# Pragma comment (Lib, "ws2_32.lib ")

# Include <stdio. h>
# Include <winsock2.h>

Socket g_sockclient = invalid_socket;

Void usage ();

Bool winapi ctrlhandler (DWORD dwevent );

Int main (INT argc, char * argv [])
{
Unsigned long destaddr;
Int nport;
If (argc = 2)
{
Destaddr = inet_addr (argv [1]); // parse the IPv4 address into 32bit integer
// Which suitable for the struct in_addr
If (destaddr = inaddr_none)
{
Usage ();
Return-1;
}
Nport = 23;
}
Else
If (argc = 3)
{
Destaddr = inet_addr (argv [1]);
If (destaddr = inaddr_none)
{
Usage ();
Return-1;
}
Nport = atoi (argv [2]);
If (nport <= 0 | nport> 65535)
{
Usage ();
Return-1;
}
}
Else
{
Usage ();
Return-1;
}
If (! Setconsolectrlhandler (ctrlhandler, true ))
{
Printf ("setconsolectrlhandler: % d/N", getlasterror ());
Return-1;
}

Wsadata;
Wsastartup (winsock_version, & wsadata );

G_sockclient = socket (af_inet, sock_stream, 0 );
If (g_sockclient = invalid_socket)
{
Wsacleanup ();
Return-1;
}

Struct sockaddr_in;
Memset (& to, 0, sizeof ());
To. sin_addr.s_un.s_addr = destaddr;
To. sin_family = af_inet; // set the address family
To. sin_port = htons (nport); // change the unsigned short into "big-Endian"
Printf ("Connecting % s: % d ......", inet_ntoa (to. sin_addr), nport );

// Connect the destinate IP Address
If (connect (g_sockclient, (struct sockaddr *) & to, sizeof (to) = socket_error)
{
If (g_sockclient! = Invalid_socket)
Closesocket (g_sockclient );
Printf ("failed. (connect % d)/n", wsagetlasterror ());
Wsacleanup ();
Return-1;
}
Else
Printf ("successfully./ninput:/N ");

Char bufa [83];
Char bufb [1000];
Fd_set readset;
Struct timeval TV;
Int ret, Len;
While (1) // loop and handle the network event
{
Memset (bufa, 0, 83 );
Gets (bufa );
Len = strlen (bufa );
If (LEN> 80)
Len = 80;
Bufa [Len] = '/R ';
Bufa [Len + 1] = '/N ';
Bufa [Len + 2] = 0;
Ret = Send (g_sockclient, bufa, strlen (bufa), 0); // send the data of bufa to the destinate address
If (ret = socket_error)
{
Printf ("Send: % d/N", wsagetlasterror ());
Break;
}

Fd_zero (& readset );
Fd_set (g_sockclient, & readset );
TV. TV _sec = 3;
TV. TV _usec = 0;
Ret = select (0, & readset, null, null, & TV );

If (ret = socket_error)
{
Printf ("select: % d/N", wsagetlasterror ());
Break;
}
If (ret = 0)
{
Printf ("timeout, no response from server./N ");
Break;
}
If (fd_isset (g_sockclient, & readset ))
{
Memset (bufb, 0,1000 );
Ret = Recv (g_sockclient, bufb, 1000,0 );
If (ret = socket_error)
{
Printf ("Recv: % d/N", wsagetlasterror ());
Break;
}
Else
Printf ("% s/n", bufb );
}
}
If (g_sockclient! = Invalid_socket)
Closesocket (g_sockclient );
Wsacleanup ();
Printf ("stopped./N ");

Return 0;
}

/* Print the usage of mytelnet */
Void usage ()
{
Printf ("Usage:/tmytelnet x. x. x port/t (0 <port <65535)/n ");
}

Bool winapi ctrlhandler (DWORD dwevent)
{
Switch (dwevent)
{
Case ctrl_c_event:
Case ctrl_logoff_event:
Case ctrl_shutdown_event:
Case ctrl_close_event:
Printf ("Stopping.../N ");
Closesocket (g_sockclient );
G_sockclient = invalid_socket;
Break;
Default:
Return false;
}
Return true;
}

Next, we will compile the program, log on to the BBS in Tsinghua, enter Telnet 161.111.8.238, and press Enter. The image I got is as follows:

This seems a bit wrong, huh, and I will discuss the details later. Next let's take a look at the structure of this client.

1. We use # pargma comment (Lib, "ws2_32.lib") to instruct the connector to find and use the ws2_32.lib static library. If you do not use the encoding method, you can also choose to add ws2_32.lib to the link option set in the project.

2. Socket g_sockclient = invalid_socket; declares the global variable g_sockclient of the set interface type.

3. Read the target IP address and port of the input parameter and save them in destaddr and nport respectively.

4. Call the setconsolectrlhandler function to set the response function for some special events for mytelnet. These special events include ctrl_c_event and ctrl_close_event.

5. Call the wsastartup function to initialize Winsock.

6. Create the TCP interface g_sockclient of the client.

7. Fill in the inet address structure to, that is, set the IP address and port of the TCP server to be connected.

8. Connect to the TCP Server Based on the address.

9. In the loop body, we read user input data from the console, send the data to the server, and then receive and print the server feedback.

10. ret = select (0, & readset, null, null, & TV); The select function is used for time-out control.

11. Call the closesocket function to disable the g_sockclient interface.

12. Call the wsacleanup function to end the use of WinSock.

Bool winapi ctrlhandler (DWORD dwevent) is the response function of the console event. If mytelnet receives the ctrl_c_event, ctrl_logoff_event, ctrl_shutdown_event, or ctrl_close_event event, the client closes the g_sockclient interface (which will cause an error in calling the Winsock function of g_sockclient in the main program and exit the loop ), and assign it to invalid_socket.

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.