Simple example of a C + + TCP client and server

Source: Internet
Author: User
Tags set socket win32 error server port htons

Create 2 new items using VS2010, one called "TCPServer" and the other called "TcpClient".

Right-click on the "Project"-"Properties"-"Configuration Properties"--"linker"--"input" and "Additional Dependencies", click on the "Edit" button in the right drop-down box to add "Ws2_32.lib" and click OK.

1. Project TCPServer

Tcpserver.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <WinSock2.h> #include <stdio.h> #define SERVERPORT 6222//server port int _tmain (int ARGC, _tchar* argv[]) {//used to save the version number of the Winsock library Word wversionrequested; Wsadata wsadata;int err;printf ("This is a Server side application!\n"); wversionrequested = Makeword (2,2); err = WSAStartup (wversionrequested, &wsadata), if (err! = 0) {printf ("WSAStartup () called failed!\n"); return-1;} else {printf (" WSAStartup () called successful!\n ");} if (Lobyte (wsadata.wversion)! = 2 | | Hibyte (wsadata.wversion)! = 2) {//If it is not the requested version number 2.2, terminate the use of the Winsock library WSACleanup (); return-1;} Create socket for listening socket sockserver = socket (af_inet, sock_stream, 0), if (sockserver = = Invalid_socket) {printf ("socket () Called failed!, error code is:%d ", WSAGetLastError ()); return-1;} else {printf ("socket () called successful!\n");} Populate the server-side socket structure SOCKADDR_IN addrserver;//converts host byte order to TCP/IP network byte order addrserver.sin_addr. S_un. S_ADDR = htonl (inaddr_any); addrserver.sin_family = Af_inet;addrserver.sin_port = Htons (ServerPort);//Bind the socket to a local address and port on err = Bind (Sockserver, (sockaddr*) &addrserver, sizeof (SOCKADDR)); if (err = = Socket_error) {printf ("bind () called failed! The error code is:%d\n ", WSAGetLastError ()); return-1;} else {printf ("bind () called successful\n");} Set socket to listen mode, prepare to receive client request Err = Listen (Sockserver, 5), if (err = = Socket_error) {printf ("listen () called failed! The error code is:%d\n ", WSAGetLastError ()); return-1;} else {printf ("listen () called successful!\n");} Save socket information for the client sending the request link sockaddr_in addrclient;int len = sizeof (SOCKADDR); bool Isstart = True;while (Isstart) {// Wait for client request to arrive SOCKET Sockconn = Accept (Sockserver, (sockaddr*) &addrclient, &len); if (sockconn = = Invalid_socket) { printf ("Accept () called failed! The error code is:%d\n ", WSAGetLastError ());} else {printf ("The server receive a new client connection!\n");} Char sendbuf[100];sprintf_s (SENDBUF, +, "Welcome%s", Inet_ntoa (ADDRCLIENT.SIN_ADDR));//Send data to send (Sockconn, sendbuf , strlen (sendbuf) +1, 0); Char recvbuf[100];//Receive Data recv (Sockconn, recvbuf, 100, 0);//print received data printf ("Receive data from client side [%s,%d] is:%s\n", Inet_ntoa (addr CLIENT.SIN_ADDR), Addrclient.sin_port, recvbuf);//close connection Socket closesocket (sockconn);} return 0;}

2. Project TcpClient

Tcpclient.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <WinSock2.h> #include <stdio.h> #define SERVER_PORT 6222//server port number # # BUFF _size 1024#pragma Comment (lib, "Ws2_32.lib") int _tmain (int argc, _tchar* argv[]) {//Load socket font word wversionrequested; Wsadata wsadata;int err;printf ("This is a Client side application!\n"); wversionrequested = Makeword (2, 2); err = WSAStartup (wversionrequested, &wsadata); if (err! = 0) {//tell The user, we could not find a usable WinSock dll.printf ("Wsasta Rtup () called failed!\n "); return-1;} else {printf ("WSAStartup called successful!\n");} if (Lobyte (wsadata.wversion)! = 2 | | Hibyte (wsadata.wversion)! = 2) {//tell The user that we could not find a usable WinSock dll.wsacleanup (); return-1;} The WinSock Dll is acceptable. PROCEED//Create socket Socket sockclient = socket (af_inet, sock_stream, 0); if (sockclient = = Invalid_socket) {printf ("socket () Called failed!, error code is%d\n ", WSAGetLastError ()); return-1;} else {printf ("socket () called successFul!\n ");} The service-side socket structure information that needs to be connected sockaddr_in addrserver;//set up the server ipaddrserver.sin_addr. S_un. S_ADDR = inet_addr ("127.0.0.1"); addrserver.sin_family = af_inet;//Sets the port number of the server (using network byte order) Addrserver.sin_port = Htons ( SERVER_PORT);//Make a connection request to the server Err = Connect (sockclient, (sockaddr*) &addrserver, sizeof (SOCKADDR)); if (err = = socket_ ERROR) {printf ("connect () called failed! The error code is%d\n ", WSAGetLastError ());} else {printf ("connect () called successful\n");} Receive data char recvbuf[buff_size] = {0};RECV (sockclient, recvbuf, 0);p rintf ("Receive data from server side is:%s\n", rec VBUF);//Send data char buf[] = "This is a client side!\n"; Send (Sockclient, buf, strlen (buf) +1, 0);//Close Socket closesocket ( sockclient);//termination of the socket font using WSACLEANUP (); System ("pause"); return 0;}
3. Running the actual

(1) Successful connection


(2) Client connection failed


The following are excerpts from the Baidu EncyclopediaWsasetlasterror ()The return valueHttp://baike.baidu.com/link?url=nzC97QpyaeSZaX6ppD9mrrdghZsFXroQ1zG1xi61dAyOvH8cLmRAn_ Iudnrhrwvovrgete0gzfgclrcqcwbowa
return valueEdit 6-wsa_invalid_handle The specified event object is invalid. If you use the Winsock function that corresponds to the WIN32 function, you may have such a Win32 error. It indicates that a handle passed to the wsawaitformultipleevents is not valid. 8-wsa_not_enough_memory not enough memory. This Win32 error indicates that the amount of memory is insufficient to complete the specified operation. 87-wsa_invalid_parameter one or more parameters is invalid. This Win32 error indicates that the arguments passed to the inside of the function are invalid. If the event count parameter is not valid, this error can also occur when the wsawaitformultipleevents is executed. The 258-wsa_wait_timeout operation timed out. This Win32 error indicates that the overlapped I/O operation did not complete within the specified time. The 995-wsa_operation_aborted overlap operation was canceled. This Win32 error indicates that the cancellation of an overlapped I/O operation resulted from the closure of the socket. In addition, this error may occur when executing the sio_flush I/O control command. 996-wsa_io_incomplete overlapped I/O event object is not in the messaging state. This Win32 error is also closely related to overlapped I/O operations and is generated when the Wsagetoverlappedresults function is called, indicating that the overlapped I/O operation has not been completed. The 997-wsa_io_pending overlap operation will be completed at a later time. When an overlapped I/O operation is made with the Winsock function, the WIN32 error indicates that the operation has not been completed and will be completed at a later time. 10004-wsaeintr function call interrupted. This error indicates that a call was forcibly interrupted due to a call to WSACancelBlockingCall. 10009-WSAEBADF file handle error. This error indicates that the supplied file handle is invalid. Under MICROSOFTWINDOWSCE, the socket function may return this error, indicating that the shared serial port is in a "busy" state. 10013-wsaeacces permission was denied. An attempt was made to operate on a socket, but is forbidden. This type of error can occur if you attempt to use a broadcast address in sendto or wsasendto, but you have not set broadcast permissions with both the setsockopt and so_broadcast options. The 10014-wsaefault address is not valid. The pointer address passed to the Winsock function is invalid. This error can also occur if the specified buffer is too small. 10022-wsaeThe inval parameter is not valid. An invalid parameter was specified. For example, this error occurs if an invalid control code is specified for the WSAIOCTL call. In addition, it may indicate that there is an error in the current state of the socket, such as when you call accept or wsaaccept on a socket that is not listening. 10024-wsaemfile open too many files. You are prompted to open too many sockets. Typically, Microsoft providers are limited only by the amount of resources available within the system. The 10035-wsaewouldblock resource is temporarily unavailable. For non-blocking sockets, this error is usually returned if the request operation cannot be performed immediately. For example, calling connect on a non-blocking socket will return this error. Because the connection request cannot be executed immediately. The 10036-wsaeinprogress operation is in progress. A non-locking operation is currently being performed. This error generally does not occur unless you are developing a 16-bit Winsock application. The 10037-wsaealready operation is complete. In general, this error occurs when an operation that is already in progress is attempted on a non-locking socket. For example, on a non-locked socket that is already in a connected process, call connect or WSAConnect again. Also, the service provider is in the process of executing a callback function (for a Winsock function that supports callback routines). 10038-wsaenotsock socket operation on invalid socket. Any Winsock function that treats the socket handle as a parameter will return this error. It indicates that the supplied socket handle is invalid. 10039-wsaedestaddrreq requires a destination address. This error indicates that no specific address is provided. For example, if the destination address is set to Inaddr_any (any address) when calling SendTo, this error will be returned. 10040-wsaemsgsize message too long. The meaning of this error is many. This error occurs if a message is sent on a datagram socket that is too large for the internal buffer. For example, because the network itself is limited, so that a message too long, it will also produce this error. Finally, this error can also occur if the buffer is too small to receive the message after the datagram is received. 10041-wsaeprototype socket protocol type is incorrect. The specified socket type is not supported by the protocol specified in the socket or WSASocket call. For example, it is required to create an IP socket of type SOCK_STREAM, while specifying that the protocol is IPPROTO_UDP, this error will occur. 10042-WSAENOPROTOOPT protocol option error.Indicates that the specified socket option or level is unknown, unsupported, or invalid in a getsockopt or setsockopt call. 10043-wsaeprotonosupport does not support the protocol. The requested protocol is not installed in the system or there is no corresponding implementation. For example, if TCP/IP is not installed on the system and you try to establish a TCP or UDP socket, this error will occur. 10044-wsaesocktnosupport socket type not supported. There is no corresponding specific socket type support for the specified address family. For example, this error occurs when a Sock_raw socket type is created for a protocol request that does not support the original socket. 10045-wsaeopnotsupp operations not supported. Indicates that an attempted action was not supported for the specified object. Typically, this error occurs when you try to invoke Winsock on a socket that does not support invoking a Winsock function. For example, this error occurs when you invoke the Accept or wsaaccept function on a datagram socket. 10046-wsaepfnosupport does not support the protocol family. The requested protocol family does not exist or is not installed in the system. In most cases, this error can be interchanged with Wsaeafnosupport (the two are equivalent), the latter appearing more frequently. The requested operation is not supported by the 10047-wsaeafnosupport address family. This error occurs when you try to execute an operation that is not supported by a socket type. For example, this error occurs when a sendto or WSASendTo function is called on a socket of type Sock_stream. In addition, when invoking the socket or WSASocket function, this error can also occur if an invalid address family, socket type, and protocol combination are requested at the same time. 10048-wsaeaddrinuse the address is in use. Normally, only one socket address is allowed per socket (for example, an IP socket address consists of a local IP address and a port number). This error is generally related to the three functions of bind, connect, and WSAConnect. Socket options can be set in the SetSockOpt function SO_REUSEADDR, allowing multiple sockets to access the same local IP address and port number. 10049-wsaeaddrnotavail cannot assign the requested address. This error occurs when the address specified in the API call is not valid for that function. For example, if you specify an IP address in the bind call, but you do not have a corresponding local IP interface, this error occurs. In addition, through Connect, wsaconnThe four functions, ect, SendTo, WSASendTo, and wsajoinleaf, also produce such errors as specifying port 0 o'clock for the remote computer on which the connection is being prepared. 10050-wsaenetdown network disconnected. When trying to take an action, you find that the network connection is interrupted. This could be caused by a network stack error, a failure of the network interface, or a problem with the local network. 10051-wsaenetunreach network is not reachable. When trying to take an action, it is found that the target network is unreachable (inaccessible). This means that the local host does not know how to reach a remote host. In other words, there is currently no known route to reach that target host. 10052-wsaenetreset the connection was disconnected when the network was reset. The network connection was interrupted because an error was detected by the keep-active operation. This error can also occur if you set the So_keepalive option through the SetSockOpt function on a connection that is already invalid. 10053-wsaeconnaborted software causes connection cancellation. An already established connection was canceled due to a software error. Typically, this means that the connection was canceled due to a protocol or time-out error. The 10054-wsaeconnreset connection is reset by the other side. An already established connection was forcibly shut down by the remote host. This can occur if the process on the remote host aborts abnormally (due to a memory conflict or hardware failure), or if a forced shutdown is performed on the socket. For forced shutdown, you can configure a socket with the SO_LINGER socket option and the setsockopt. 10055-wsaenobufs No buffer space. The requested operation cannot be performed because the system lacks sufficient buffer space. The 10056-wsaeisconn socket is already connected. Indicates that an attempt was made to establish a connection on a socket that has already been established. It is important to note that this error can occur with both datagrams and data flow sockets. When using a datagram socket, if the address of an endpoint is associated with a datagram communication by means of a connect or WSAConnect call, then an attempt to call SendTo or WSASendTo again will result in such an error. 10057-wsaenotconn socket is not yet connected. This can be caused by sending a data request on a "connection-oriented" socket that has not yet established a connection. 10058-wsaeshutdown the socket cannot be sent after it is closed. Indicates that the socket was partially closed through a call to shutdown, but the data was sent and received afterwards. It is important to note that this error only occurs in the direction of the data flow that has been closed. As an example, the number of completedIf you call shutdown after sending, any subsequent call to the data will produce such an error. The 10060-wsaetimedout connection timed out. This error occurs if a connection request is made, but the specified time has not yet been properly responded to by the remote computer (or no response at all). To receive such an error, you usually need to set the So_sndtimeo and So_rcvtimeo options on the socket first, and then call the Connect and WSAConnect functions. To learn more about setting the So_sndtimeo and So_rcvtimeo options on a socket, refer to chapter 9th. 10061-wsaeconnrefused connection was refused. The connection could not be established because it was rejected by the target machine. This is usually due to the fact that there is no application on the remote machine that can service the connection on top of that address. 10064-wsaehostdown host is off. This error indicates that the operation failed because the target host was shut down. However, the application is more likely to receive a wsaetimedout (connection timeout) error at this time, because the other side of the shutdown situation is usually when trying to establish a connection. The 10065-wsaehostunreach does not have a route to the host. The application attempted to access a non-reachable host. This error is similar to Wsaenetunreach. 10067-wsaeproclim process too many. Some Winsock service providers limit the number of processes that can access them at the same time. The 10091-wsasysnotready network subsystem is not available. When calling WSAStartup, this error is returned if the provider does not work properly (because the primary system that provides the service is not available). 10092-wsavernotsupportedwinsock.dll version is incorrect. Indicates that the requested Winsock provider version is not supported. 10093-wsanotinitialisedwinsock has not been initialized. A call to WSAStartup has not been completed successfully. The 10101-wsaediscon is closing gracefully. This error is returned by WSARecv and WSARecvFrom, which indicates that the remote host has initialized a graceful shutdown operation. This error occurs on a "message-oriented" protocol such as ATM. 10102-wsaenomore can't find more records. This error is returned from the WSALookupServiceNext function, which indicates that no more records have been left. This error can usually be used interchangeably with Wsa_e_no_more. In the application, you should check both this error and the Wsa_e_no_more。 The 10103-wsaecancelled operation was canceled. This error indicates that a call to WSALookupServiceEnd (service abort) was issued while the WSALookupServiceNext call was still processing. At this point, WSALookupServiceNext will return this error. This error code can be used interchangeably with wsa_e_cancelled. As an application, you should check both this error and the Wsa_e_cancelled10105-wsaeinvalidprovider invalid service provider. This error is associated with the service provider and is generated when the provider fails to establish the correct Winsock version, which does not work properly. 10106-wsaeproviderfailedinit provider initialization failed. This error is associated with the service provider, usually when the provider cannot load the required DLL. 10107-wsasyscallfailure system call failed. A system call that indicates that absolutely should not fail has unfortunately failed. 10108-wsaservice_not_found could not find such a service. This error is usually related to registration and name resolution functions and is generated when querying services (the 10th chapter explains these functions in detail). This error indicates that the requested service could not be found within the given namespace. 10109-wsatype_not_found the type of the class could not be found. This error is also associated with a registration and name resolution function, which occurs when the service class is processed. If you register an instance of the good one service, it must refer to a service that was previously installed through Wsainstallserviceclass. 10110-wsa_e_no_more can't find more records. This error is returned from the WSALookupServiceNext call, indicating that there are no remaining records. This error can often be used interchangeably with Wsaenomore. As an application, you should check both this error as well as the Wsaenomore. The 10111-wsa_e_cancelled operation was canceled. This error indicates that a call to the WSALookupServiceEnd (abort service) was issued when the call to WSALookupServiceNext was not completed. This way, WSALookupServiceNext returns the error. This error code can be used interchangeably with wsaecancelled. As an application, you should check both this error as well as the wsaecancelled. 10112-wsaerefused query was rejected. As a result of being actively rejected, so a database query operation failed. 11001-wsahost_not_found host not found. This error was generated when calling gethostbyname and gethostbyaddr, indicating that an authoritative answer host (authoritativeanswerhost) was not found. 11002-wsatry_again non-authorized host not found. This error is also generated when calling gethostbyname and gethostbyaddr, indicating that a non-authoritative host was not found, or that a server failure was encountered. 11003-wsano_recovery encountered an unrecoverable error. This error is also generated when calling gethostbyname and gethostbyaddr, indicating that an unrecoverable error has occurred and that the operation should be attempted again. 11004-wsano_data did not find a data record for the requested type. This error is also generated when calling gethostbyname and gethostbyaddr, indicating that the data record corresponding to the request type was not found, although the provided name was valid. 11005-wsa_qos_receivers at least one reservation message arrives. This value is closely related to IP quality of Service (QoS) and is not really a "mistake" (see chapter 12th for the details of QoS). It indicates that at least one process on the network wants to receive QoS traffic. 11006-wsa_qos_senders at least one path message arrives. This value is associated with QoS, which in fact is more like a status report message. It points out that at least one process in the network wants to send QoS data. 11007-wsa_qos_no_senders there is no QOS sender. This value is associated with QoS and indicates that no more processes are interested in the delivery of QoS data. See chapter 12th for a complete set of instructions on what happened when such an error occurred. 11008-wsa_qos_no_receivers does not have a QOS receiver. This value is associated with QoS and indicates that no more processes are interested in receiving the QoS data. Please refer to Chapter 12th for a complete description of this error. 11009-wsa_qos_request_confirmed Reservation request has been confirmed. A QoS application can make a request beforehand, hoping to receive a notification after approving its own reservation request for network bandwidth. If such a request is made, it will receive such a message once it has been approved. See chapter 12th for a detailed description of this message. 11010-wsa_qos_admission_failure lack of resources is a mistake. Not enough resources to meetQoS bandwidth requests. The 11011-wsa_qos_policy_failure certificate is invalid. Indicates that a QoS reservation request was issued, either the user does not have the correct permissions, or the supplied certificate is invalid. 11012-wsa_qos_bad_style The unknown or conflicting style. A QoS application can create different filter styles for a given session. If this error occurs, the specified style type is either unknown or has a conflict. See chapter 12th for a detailed description of the filter style. 11013-wsa_qos_bad_object invalid Filterspec struct or provider-specific object. If the FILTERSPEC structure provided for the QoS object is invalid, or if the provider-specific buffer is invalid, the error will be returned as described in chapter 12th. There's a problem with 11014-wsa_qos_traffic_ctrl_errorflowspec. If the communication control component finds a problem with the specified Flowspec parameter (passed as a member of the QoS object), the error is returned. 11015-wsa_qos_generic_error General QOS errors. This is a more general error, and if no other QoS error is appropriate, the error is returned.

Simple example of a C + + TCP client and server

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.