Create a simple VC + + Socket program __c++

Source: Internet
Author: User
Tags socket error htons

This article mainly combines with MSDN on several official documents about WinSocket, creates a simple VC + + Socket Sample program, demonstrates a basic CS model. Reference links are as follows:

Msdn:windows Socket 2 Getting Started with WinSocket

Other Blog: VC network programming C + + Socket


First, c/s--client and server

In network programming, the most common is the C/S model, which has one (or more) client and one server. In fact, we need to create two different socket network applications to demonstrate the example (we can put these two projects under a solution by first creating a project, then modifying the name, and then adding another project under the solution). The two applications--client and server have different behaviors, as follows:

Server

Initialize Winsock. Create a socket. Bind the socket. Listen on the socket for a client. Accept a connection from a client. Receive and send data. Disconnect. Client

Initialize Winsock. Create a socket. Connect to the server. Send and receive data. Disconnect.

Second, header files and libraries

Create a new two normal I Win32 console program for client and server, including the following header files and libraries:

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

#pragma comment (lib, " Ws2_32.lib ")

where "stdio.h" is used for standard input and output, such as the printf () function. Note that "winsock2.h", official explanation: Click on the Open link

The Winsock2.h header file internally includes core elements from the Windows.h header file, so there isn't usually an #i Nclude line for the Windows.h header file in Winsock applications. If a #include line is needed for the Windows.h header file, this should being preceded with the #define Win32_lean_and_mean Macro. For historical reasons, the WINDOWS.H header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in the Winsock.h header file would conflict with the declarations in the Winsock2.h header file required B Y Windows Sockets 2.0. The Win32_lean_and_mean macro prevents the Winsock.hfrom being included by the WINDOWS.H header. An example illustrating the this is shown below.


Note that you need to bring the number "2".


Third, client code

#include <stdio.h> #include <Winsock2.h> #include <iostream> #include <fstream> using namespace
Std
#pragma comment (lib, "Ws2_32.lib")//WinSocket is a dynamic link library that needs to load its library and contain the corresponding header file char recvbuf[1310721];
    int _tmain (int argc, _tchar* argv[]) {wsadata WSD;                                            SOCKET sockclient;
    Client socket sockaddr_in addrsrv;
    Char recvbuf[1310721];
    memset (recvbuf, 0, 1310721); if (WSAStartup Makeword (2,2), &AMP;WSD)!=0)//1> initialize the Windows Socket library (API set) {printf ("Start up failed!\
        n ");
    return 0;                    } sockclient=socket (af_inet,sock_stream,0);
        2> Create a SOCKET if (invalid_socket = = sockclient) {printf ("Create client SOCKET error!\n");
    return 0; } addrsrv.sin_addr. S_un.
    S_ADDR=INET_ADDR ("192.168.18.129");
    Addrsrv.sin_family=af_inet;
    Addrsrv.sin_port=htons (6000); if (Socket_error = = Connect (sockclient, (sockaddr*) &addrsrv,sizeOf (SOCKADDR))//connection server side {printf ("Connect server error!\n");
    return 0;
    } ofstream ofs ("Recv.txt");
        while (1) {printf ("Wait for recv data\n");                                int recvnum = recv (sockclient,recvbuf,1310721,0);
            Receive server-side data if (Recvnum = = 1310721-1) {printf ("%s\n", recvbuf);
            Ofs.write ("*******", strlen ("*******"));
            Ofs.write (Recvbuf, recvnum);
            Ofs.write ("\ n", strlen ("\ n"));
        Ofs.flush ();
    Sleep (1000);
    } ofs.flush ();
    Ofs.close ();    Send (Sockclient, "Hello World", strlen ("Hello World") +1,0);                                    Sending data closesocket (sockclient) to the server side;

	Close connection WSACleanup ();
return 0;
 }

Three, the server code

#include <stdio.h> #include <Winsock2.h> #include <iostream> #include <fstream> using namespace
Std
#pragma comment (lib, "Ws2_32.lib") char sendbuf[1310721];
    int _tmain (int argc, _tchar* argv[]) {wsadata WSD;                                            SOCKET server;    
    Server socket sockaddr_in addrsrv;
    Char sendbuf[1310721];
    memset (&sendbuf[0], ' 3 ', 1310721);
    memset (&sendbuf[0], ' 9 ', 100000);
    memset (&sendbuf[100000], ' 0 ', 100000);
    memset (&sendbuf[200000], ' 4 ', 100000);
    memset (&sendbuf[300000], ' 1 ', 100000);
    memset (&sendbuf[400000], ' 8 ', 100000);
    memset (&sendbuf[500000], ' 5 ', 100000);
    memset (&sendbuf[600000], ' 2 ', 100000);
    memset (&sendbuf[700000], ' 6 ', 100000);
    memset (&sendbuf[800000], ' 3 ', 100000);
    memset (&sendbuf[900000], ' 7 ', 100000);
    memset (&sendbuf[1000000], ' 5 ', 310721);
    Sendbuf[1310721-1] = ' the ';
    Sockaddr_in addrclient; SOCKET Client
    Connected client socket int len; if (WSAStartup Makeword (2,2), &AMP;WSD)!=0)//1> initialize the Windows Socket library (API set) {printf ("Start up failed!\
        n ");
    return 0;
    } Server = socket (af_inet,sock_stream,0);
        if (Invalid_socket = = Server)//2> Create socket {printf ("Create server SOCKET error!\n");
    return 0; } addrsrv.sin_addr. S_un.            S_addr=htonl (Inaddr_any);
    Set address addrsrv.sin_family=af_inet;                            Addrsrv.sin_port=htons (6000);  Set the port number if (Socket_error = = bind (server, (sockaddr*) &addrsrv,sizeof (SOCKADDR))//3> will be a SOCKET with an application (IP
        + port_number) Binding {printf ("bind error!\n");
    return 0;
        } if (Socket_error = = Listen (server,5))//4> set the SOCKET to listener mode, set the maximum number of connections {
        printf ("Listen error!\n");
    return 0; } len=sizeof (SockaddR);
    printf ("Wait for Accept client\n");    Client = Accept (server, (sockaddr*) &addrclient,&len); 5> hears the request, accepts the request, and returns the socket if (invalid_socket!= client) {printf ("Welcome%s \ \ \ \ \ r \ n") for the connection here, Inet_ntoa (addr
    CLIENT.SIN_ADDR));
    } ofstream ofs ("Send.txt");            while (1) {int sendnum = Send (Client,sendbuf,strlen (SENDBUF), 0); 6> communicates with the returned socket and client, sending information to the client if (Sendnum = = strlen (sendbuf)) {//recv (client,recvbuf,100,0)                            ;
            6> uses the returned sockets and client communications to receive client data printf ("%s\n", sendbuf);
            Ofs.write ("*******", strlen ("*******"));
            Ofs.write (SendBuf, sendnum);
            Ofs.write ("\ n", strlen ("\ n"));
        Ofs.flush ();
    Sleep (1000);
    } ofs.flush ();
    Ofs.close ();                                    Closesocket (client);
    

	Close connection WSACleanup ();
return 0;
 }



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.