Data transfer __c++ of C + + Tcp&udp&http

Source: Internet
Author: User

**TCP and UDP Difference Summary:
1, TCP connection-oriented (such as phone calls to establish a connection before the dial); UDP is connectionless, that is, no connection needs to be established before data is sent
2, TCP provides a reliable service. In other words, the data transmitted through the TCP connection has no errors, no loss, no repetition, and arrives in order; UDP does its best to deliver, IE does not guarantee reliable delivery
3, TCP-oriented word throttling, in fact, TCP data as a series of unstructured byte stream; UDP is a message-oriented
UDP does not have congestion control, so the network congestion does not cause the source host to send a low rate (useful for real-time applications, such as IP telephony, real-time video conferencing, etc.)
4, each TCP connection can only be point-to-point; UDP supports one-to-one, One-to-many, Many-to-many and Many-to-many Interactive communication
5, TCP header cost 20 bytes; UDP's header cost is small, only 8 bytes
6, TCP logical communication channel is full duplex reliable channel, UDP is unreliable channel * *

TCP protocol

#include <WinSock2.h> #include <stdio.h> #include <stdlib.h> #pragma comment (lib, "Ws2_32.lib") void S

    Ever () {wsadata wsadata; 

    Char buf[] = "Server:hello, I am a Server ...";
        if (WSAStartup (Makeword (2, 2), &wsadata)!= 0) {printf ("Failed to load Winsock");
    Return

    //Create socket socket for listening SOCKSRV = socket (af_inet, sock_stream, 0);
    Sockaddr_in addrsrv;
    addrsrv.sin_family = af_inet; Addrsrv.sin_port = htons (Tcp_port); More than 1024 of the port number, you need to set up, reference UDP addrsrv.sin_addr. S_un. S_ADDR = htonl (inaddr_any);//This is received from the native, can set its own needs IP int retVal = bind (Socksrv, (lpsockaddr) &addrsrv, sizeof (Sockadd
    r_in));
        if (RetVal = = socket_error) {printf ("Failed bind:%d\n", WSAGetLastError ());
    Return
        } if (Listen (socksrv,10) ==socket_error) {printf ("Listen failed:%d", WSAGetLastError ());
    Return
    } sockaddr_in addrclient;

    int len = sizeof (SOCKADDR);
    while (1) {    Waiting for a client request to come SOCKET Sockconn = Accept (Socksrv, (SOCKADDR *) &addrclient, &len);
            if (Sockconn = = socket_error) {printf ("Accept failed:%d", WSAGetLastError ());
        Break

        printf ("Accept client ip:[%s]\n", Inet_ntoa (ADDRCLIENT.SIN_ADDR));
        Send the data, here can be commented out int isend = Send (Sockconn, buf, sizeof (BUF), 0);
            if (isend = = socket_error) {printf ("Send failed");
        Break
        } Char recvbuf[100];
memset (recvbuf, 0, sizeof (RECVBUF));
        Receive Data recv (Sockconn, Recvbuf, sizeof (RECVBUF), 0);

        printf ("%s\n", recvbuf);
    Closesocket (Sockconn);
    } closesocket (SOCKSRV);
WSACleanup ();
    } void Client () {//load socket wsadata wsadata;
    Char buff[1024];

    memset (buff, 0, sizeof (buff));
        if (WSAStartup (Makeword (2, 2), &wsadata)!= 0) {printf ("Failed to load Winsock");
    Return
 } sockaddr_in addrsrv;   addrsrv.sin_family = af_inet; Addrsrv.sin_port = htons (tcp_port);//The Port addrsrv.sin_addr to send. S_un.
    S_ADDR = inet_addr ("127.0.0.1");/set IP to send//create socket Socket sockclient = socket (af_inet, sock_stream, 0);
        if (Socket_error = = sockclient) {printf ("SOCKET () error:%d", WSAGetLastError ());
    Return
        Send a connection request to the server if (Connect (sockclient, (struct sockaddr*) &addrsrv, sizeof (addrsrv)) = = Invalid_socket) {
        printf ("Connect failed:%d", WSAGetLastError ());
    Return
        }else {///Receive data, this remark is commented out recv (sockclient, buff, sizeof (buff), 0);
    printf ("%s\n", buff);
    }//Send data char buffer = "Hello, this is a Client ...";

    Send (sockclient, buffer, sizeof (buffer), 0);
    Close socket closesocket (sockclient);
WSACleanup (); }

Header file Udp_mode.h

#include <winsock2. h>  
#include <stdio.h>  
#include "fstream"
#pragma comment (lib, "Ws2_32.lib")  
#define Buf_ SIZE 
Loadpara Void ();
int Client (std::string& file_path);
int Server (std::string sim_name_path);

function Udp_mode.cpp

Loading parameters to facilitate config file call char facedetectip[256];
int port_client;
int port_server;
    void Loadpara () {LPCWSTR strpath (TEXT ("./setting.ini"));
    LPCWSTR Strtitle (TEXT ("Parameter"));

    LPCWSTR Strkey;
    const int Buff_len = 128;//reads the cache of strings TCHAR Buff[buff_len];

    int ilength = 0; strkey = TEXT ("Facedetectip");//facedetectip getprivateprofilestring (Strtitle, strkey, L "127.0.0.1", Buff, Buff_len, s
    Trpath);
    Ilength = WideCharToMultiByte (CP_ACP, 0, Buff,-1, NULL, 0, NULL, NULL);

    WideCharToMultiByte (CP_ACP, 0, Buff,-1, Facedetectip, ilength, NULL, NULL); strkey = TEXT ("port_client");

    Database port Number port_client = Getprivateprofileint (strtitle, strkey, 3306, strpath); strkey = TEXT ("Port_server");
Database port Number Port_server = Getprivateprofileint (strtitle, strkey, 3306, strpath);
    //Data receive int Server (std::string& file_path) {WORD wversionrequested;
    Wsadata Wsadata;

    int err;

    wversionrequested = Makeword (1, 1); Err = WSAStartup (wversionrequested, &wsadata);
    if (Err!= 0) {return-1;
        } if (Lobyte (wsadata.wversion)!= 1 | |
        Hibyte (wsadata.wversion)!= 1) {wsacleanup ();
    return-1;
    Socket SOCKSRV = socket (af_inet, SOCK_DGRAM, 0);
    Sockaddr_in addrsrv; Addrsrv.sin_addr. S_un.
    S_ADDR = htonl (Inaddr_any);
    addrsrv.sin_family = af_inet;

    Addrsrv.sin_port = htons (port_client);

    Bind (Socksrv, (sockaddr*) &addrsrv, sizeof (SOCKADDR));
    Sockaddr_in addrclient;
    int len = sizeof (SOCKADDR);

    Char recvbuf[64];
    Recvfrom (socksrv, Recvbuf, sizeof (RECVBUF), 0, (sockaddr*) &addrclient, &len);
    File_path = Recvbuf;
    Closesocket (SOCKSRV);
    WSACleanup ();
return 0;
    }//Data sending end void Client (std::string sim_name_path) {WORD wversionrequested;
    Wsadata Wsadata;

    int err;

    wversionrequested = Makeword (1, 1);
    Err = WSAStartup (wversionrequested, &wsadata);
    if (Err!= 0) {return-1;

 }   if (Lobyte (wsadata.wversion)!= 1 | |
        Hibyte (wsadata.wversion)!= 1) {wsacleanup ();
    return-1;
    Socket sockclient = socket (af_inet, SOCK_DGRAM, 0);
    Sockaddr_in addrsrv; Addrsrv.sin_addr. S_un.
    S_ADDR = inet_addr (Facedetectip);
    addrsrv.sin_family = af_inet;

    Addrsrv.sin_port = htons (port_server); SendTo (Sockclient, Sim_name_path.c_str (), strlen (Sim_name_path.c_str ()) + 1, 0, (sockaddr*) &addrsrv, sizeof (so
    CKADDR));
    Closesocket (sockclient);
    WSACleanup (); return 0}

Http
Need to install compilation curl:
Generate Libcurl.lib via CURL+VS2015+OPENSSL (vs2015 must need this)
Place the generated Lib and include in the configuration and add Ws2_32.lib Wldap32.lib
Add Building_libcurl to the predefined, curl_staticlib

taskhttpsender Client Send

#include <string> #include <iostream> #include <curl/curl.h> #pragma comment (lib, "Ws2_32.lib") #prag Ma comment (lib, "Wldap32.lib") #pragma comment (lib, "Libcurl.lib") bool Send (const std::string &file/* file name to save * */, S
    Td::string m_url/*http Address * * CURL_GLOBAL_INIT (Curl_global_all);
    curl* M_hcurl = Curl_easy_init ();
    curl_slist* poptionlist = NULL;
    Poptionlist = Curl_slist_append (Poptionlist, "Expect:");

    Curl_easy_setopt (M_hcurl, Curlopt_httpheader, poptionlist);
    curl_httppost* pformpost = NULL;

    curl_httppost* Plastelem = NULL; Upload file, specify local file full path Curl_formadd (&pformpost, &plastelem, Curlform_copyname, "Sendfile", Curlform_file, F

    Ile.c_str (), Curlform_contenttype, "Application/octet-stream", curlform_end); Curl_formadd (&pformpost, &plastelem, curlform_copyname, "filename", curlform_copycontents, File.c_

    STR (), curlform_end); Do not add an end to the HFS server can not write the file, generally does not exist this problem, here to join just forThe test.
    Curl_formadd (&pformpost, &plastelem, Curlform_copyname, "End", Curlform_copycontents, "End", CURLFORM_END);
    Curl_easy_setopt (M_hcurl, Curlopt_httppost, pformpost);

    Curl_easy_setopt (M_hcurl, Curlopt_url, M_url.c_str ());
    Curlcode res = curl_easy_perform (m_hcurl);
        if (res!= curle_ok) {std::cout << res << Std::endl;
    return false;
    else std::cout << "Success" << Std::endl;

    Curl_formfree (Pformpost);
return true; }

The Taskhttprecver server accepts

#include <string> #include <cstdio> #include <iostream> #include <curl/curl.h> #pragma comment ( LIB, "Ws2_32.lib") #pragma comment (lib, "Wldap32.lib") #pragma comment (lib, "Libcurl.lib") bool Recv (std::string M_f
    ilename/* to save the filename * * *, std::string m_url/*http address * * std::string filePath = m_filename;

    FILE *m_fp = fopen (Filepath.c_str (), "w");
    if (!M_FP) {return false;
    } curl_global_init (Curl_global_all);
    curl* M_hcurl = Curl_easy_init ();
    Sets the callback curl_easy_setopt to receive data (M_hcurl, Curlopt_url, M_url.c_str ());
    Curl_easy_setopt (M_hcurl, curlopt_writefunction, Downloadcallback);
    Curl_easy_setopt (M_hcurl, Curlopt_writedata, M_FP);
    Curl_easy_setopt (M_hcurl, Curlopt_maxredirs, 5);
    Curl_easy_setopt (M_hcurl, curlopt_followlocation, 1);

    Curlcode Retccode = Curl_easy_perform (M_hcurl);
    if (Retccode!= curle_ok) std::cout << retccode << Std::endl; else Std::cout << "Success "<< Std::endl;
    Curl_easy_cleanup (M_hcurl);
    Fclose (M_FP);
    M_FP = nullptr;
return true;
    } size_t Downloadcallback (void* pbuffer, size_t nsize, size_t nmembyte, void* pparam) {file* fp = (FILE*) PParam;

    size_t nwrite = fwrite (pbuffer, nsize, Nmembyte, FP);
return nwrite;
 }

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.