Socket Communication-accept+ Multithreading

Source: Internet
Author: User
Tags htons
    Accidental opportunity, re-write a comparison of Windows socket communication based on the code,
    too long no contact socket and multithreading, many blog, but found that most of the content is older,
    so decided to write a blog, by the way to sum up their own.
Content IntroductionIntroduction to basic functions of network communication C++11 multithread Introduction Socket Communication TCP version socket communication UDP version Introduction to basic functions of network communication in TCP connection mode Client Process
1. Create a socket (socket) socket (int af, int type, int protocol) The first parameter to describe the network protocol type, TCP/IP protocol can only use af_inet second parameter: The socket traffic type (TCP , UDP, and so on) the third parameter: related to the type of communication selected 2. Initiating a connection to a server sockaddr_in declaring a socket type Sin_family protocol family sin_port Communication Port Sin_a DDR Network IP htons converts an integer type to a network byte order htonl converts a long integer to a network byte sequence Inet_pton (int af, char * str, pvoid addrbuf) converts dotted decimal IP addresses to networks  Byte first parameter: protocol family The second parameter: dotted decimal IP address, for example: "127.0.0.1" the third parameter: sin_addr inte_ntop (int af, pvoid addrbuf, Char *str, size_t len converts network byte order to dotted decimal IP address first parameter: protocol family The second parameter: sin_addr third parameter: The string that stores the IP address fourth parameter Number: Byte unit length Connect (socket s, const SOCKADDR *name, int namelen) First parameter: Created socket second argument: Socket address to link third 
        Parameters: unit length 3.client with server communication send (socket s, char * str, int len, int flag) First parameter: The socket created by this machine The second parameter: the string to send Third parameter: Send string length fourth parameter: will affect the function behavior, generally set to 0 recv (socket s, char * buf, int len,int flag) First parameter: This machine creates Built Socket second parameter: Accept MessageString third parameter: Allows the maximum length of a string to be received the fourth parameter: will affect the function behavior, generally set to 0 4. Release socket closesocket release socket
 
Service-side process
1. Create socket
2. Bind sockets with local IP and port bind
    (socket s, const SOCKADDR *name, int namelen)
        first parameter: Created socket
        Second parameter: The information to bind the
        third parameter: Socket type unit length
3. Set to Listener status
    listen (socket s, int num)
        first parameter: socket (socket)
        to listen for Second parameter: Wait for the maximum length of the connection queue
4. Wait for the arrival of the customer request, accept the connection request when the request arrives, and return a new socket accept for this connection
    (int socket, sockaddr *name, int * Addrlen)
        is the first parameter, which is a descriptor for a socket that has been set to listening mode. The
        second parameter, which is a return value, points to a variable in a struct sockaddr type of struct that holds the IP address information and port information of the client initiating the connection. The
        third parameter, also a return value, points to an integer variable that holds the length of the address information returned. The
        accept function return value is a descriptor for the socket type of a client-server connection that identifies the client on the server side.
5. Mutual communication
6. Disconnect the connection
UDP Communication Client
1. Create socket
2. Bind server IP and Port already protocol family
3. Mutual communication
    sendto (socket s, const char * buf, int len, int flags, const SOCKADDR *TO, int tolen)
        first parameter: Created socket
        second argument: string to send
        third parameter: string length to send
        fourth argument: affects function behavior, typically 0
        fifth parameter: remote socket information
        Sixth parameter: Socket unit length

    recvfrom (socket s, char * buf, int len, int flags, const SOCKADDR *to,int tolen)
        first parameter: Created socket
        Second parameter: Stores the received string the
        third parameter: The maximum acceptable string length
        fourth: The behavior that affects the function, generally 0
        fifth parameter: The remote Socket Information
        Sixth parameter: socket unit length
4. Releasing sockets
Service Side
1. Create socket
2. Bind local port, IP, protocol family information
3. Communication
4. Free connections
c++11 Multithreading Introduction

We in the socket communication process often have multiple clients to the server to request the issue, in the TCP mode, will occur blocking, the solution has accetp+ multithreading or select+accept mode, this blog mainly on the former on the line, in the process of access to information, I found that many of the Internet blog introduced multithreading mechanism are many years ago, the use of special trouble, such as pthread such a library, in fact, c++11 after the official has been the line threading encapsulated up, we just need to declare that the library thread

#include <thread>    
definition std::thread xxx;
construction Std::thread (func, ...)
Wait for thread to end Xxx.join ()   
Socket Communication TCP version Server-Side
ServerTcp.cpp: Defines the entry point for a console application. #include "stdafx.h" #pragma comment (lib, "Ws2_32.lib") #include <Winsock2.h> #include <WS2tcpip.h> #inclu De <stdio.h> #include <string.h> #include <stdlib.h> #include <thread> void func (SOCKET arg, sock
    addr_in client_addr, int pos) {char recvbuf[128];
    Char sendbuf[128];
    Char tempbuf[256];
    int sockconn = arg;
        while (true) {//receives message printf from the client ("Wait receive client messages: \ n");

        Recv (Sockconn, RECVBUF, 128, 0);
        Resolves client address information char IPCLIENT[16];
        Inet_ntop (Af_inet, &client_addr.sin_addr, ipclient, sizeof (ipclient));

        printf ("%s said:%s\n", Ipclient, Recvbuf);
        Send a message to the client gets_s (SENDBUF);
    Send (Sockconn, SendBuf, strlen (sendbuf) + 1, 0); the int main () {/**********************************************************************//* WSAStartup must be an application
    The first Windows Sockets function called by the preface or DLL. It allows the application or DLL to indicate winDows The version number of the Sockets API and details of the implementation of the specific Windows Sockets.
    The application or DLL can only invoke further Windows Sockets API functions after a successful WSAStartup () call.
    * * WORD wversionrequested;
    Wsadata Wsadata;
    int err;
    wversionrequested = Makeword (1, 1);
    Err = WSAStartup (wversionrequested, &wsadata);

    if (Err!= 0) {return 0;} if (Lobyte (wsadata.wversion)!= 1 | |
        Hibyte (wsadata.wversion)!= 1) {wsacleanup ();
    return 0; /***********************************************************************///Request to store an array of threads Std::thread threads[
    10];

    int thread_num = 0;                                   /***********************************************************************//* Socket communication
    *///Application socket Socket SVR = socket (af_inet, sock_stream, ipproto_tcp);

    Sockaddr_in addr;
    The underlying information to bind addr.sin_family = af_inet;
    Addr.sin_port = htons (6002); Addr.sin_addr. S_un.

    S_ADDR = htonl (Inaddr_any); to bind int len = sizeof (SOCKADDR);

    Bind (SVR, (struct sockaddr*) &addr, Len);
    Listening socket INT ret = Listen (SVR, 10);
        if (ret = = socket_error) {printf ("failed to listen \ n");
    Closesocket (SVR);

    ///Storage of socket information for the requested connection sockaddr_in Addrclient; while (true) {//Accept connection, return a socket socket Sockconn = Accept (SVR, (struct sockaddr*) &addrclient, &am
        P;len);
            if (Sockconn = = Invalid_socket) {//printf ("invalid socket\n");
        Continue
        ///Put the communication details online Chengri processing threads[thread_num] = Std::thread (func, Sockconn, Addrclient, thread_num);

        thread_num++;
        if (Thread_num = = 5) {printf ("Thread pool reaches quantity limit");

    }//Wait thread end for (int i = 0; i < thread_num i++) Threads[i].join ();
    Release socket closesocket (SVR);
    WSACleanup ();
return 0;

 }
Client
ClientTcp.cpp: Defines the entry point for a console application. #include "stdafx.h" #pragma comment (lib, "Ws2_32.lib") #include <Winsock2.h> #include <WS2tcpip.h> #inclu 
    De <stdio.h> #include <string.h> #include <stdlib.h> #include <thread> void new_client (int pos) {
    WORD wversionrequested;
    Wsadata Wsadata;
    int err;
    wversionrequested = Makeword (1, 1);
    Err = WSAStartup (wversionrequested, &wsadata);

    if (Err!= 0) {return;} if (Lobyte (wsadata.wversion)!= 1 | |
        Hibyte (wsadata.wversion)!= 1) {wsacleanup ();
    return;
    Socket Client = socket (af_inet, sock_stream, ipproto_tcp);

    Sockaddr_in Server;
    The underlying information to be connected server.sin_family = af_inet;
    Server.sin_port = htons (6002); Inet_pton (Af_inet, "127.0.0.1", &server.sin_addr);

    Dot decimal address translates to network byte order//initiate connection to server int ret = connect (Client, (struct sockaddr*) &server, sizeof (Server));
   if (ret = = socket_error) {printf ("Connection failed \ n");     Closesocket (Client);
        WSACleanup ();
    Return
    } Char recvbuf[128];

    Char sendbuf[128];
        while (true) {printf (' Please input message:\n ');
        gets_s (SENDBUF);
        sprintf_s (SendBuf, "%s_%d", SendBuf, POS);

        Send (Client, SendBuf, strlen (sendbuf) + 1, 0);
        Recv (Client, RECVBUF, 128, 0);
        Char ipserver[16];
        Inet_ntop (Af_inet, &server.sin_addr, Ipserver, sizeof (Ipserver));
    printf ("%s said:%s\n", Ipserver, Recvbuf);
    } closesocket (Client);
WSACleanup ();
    int main () {std::thread threads[10];
    int client_num = 1;

    for (int i = 0; i < client_num i++) threads[i] = Std::thread (new_client, i);

    for (int i = 0; i < client_num i++) Threads[i].join ();
return 0;

 }
Socket Communication UDP version Service Side
ServerUdp.cpp: Defines the entry point for a console application. #include "stdafx.h" #include "stdafx.h" #pragma comment (lib, "Ws2_32.lib") #include <Winsock2.h> #include <

ws2tcpip.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <thread>
    void func (SOCKET arg, sockaddr_in client_addr, int pos) {char recvbuf[128];
    Char sendbuf[128];
    int sockconn = arg;
    int len = sizeof (SOCKADDR);
        while (true) {//receives message printf from the client ("Wait receive client messages: \ n");

        Recvfrom (Sockconn, RECVBUF, 128, 0, (struct sockaddr*) &arg, &len);
        Resolves client address information char IPCLIENT[16];
        Inet_ntop (Af_inet, &client_addr.sin_addr, ipclient, sizeof (ipclient));

        printf ("%s said:%s\n", Ipclient, Recvbuf);
        Send a message to the client gets_s (SENDBUF);
    SendTo (Sockconn, SendBuf, strlen (sendbuf) + 1, 0, (struct sockaddr*) &arg, Len); int main () {/*****************************************//* WSAStartup must be the first Windows Sockets function called by an application or DLL.
    It allows an application or DLL to indicate the version number of the Windows Sockets API and the details of obtaining a specific Windows Sockets implementation.
    The application or DLL can only invoke further Windows Sockets API functions after a successful WSAStartup () call.
    * * WORD wversionrequested;
    Wsadata Wsadata;
    int err;
    wversionrequested = Makeword (1, 1);
    Err = WSAStartup (wversionrequested, &wsadata);

    if (Err!= 0) {return 0;} if (Lobyte (wsadata.wversion)!= 1 | |
        Hibyte (wsadata.wversion)!= 1) {wsacleanup ();
    return 0; /***********************************************************************///Request to store an array of threads Std::thread threads[
    10];

    int thread_num = 0;                                   /***********************************************************************//* Socket communication
    *///Application socket Socket SVR = socket (af_inet, SOCK_DGRAM, 0);

    Sockaddr_in addr;
    The underlying information to bind addr.sin_family = af_inet; Addr.sin_port = hTons (6002); Addr.sin_addr. S_un.

    S_ADDR = htonl (Inaddr_any);
    to bind int len = sizeof (SOCKADDR);

    Bind (SVR, (struct sockaddr*) &addr, Len);

    Stores the socket information for the requested connection sockaddr_in Addrclient;
    Put the communication details online Chengri processing threads[thread_num] = Std::thread (func, SVR, Addrclient, thread_num);

    thread_num++;

    Wait for thread end for (int i = 0; i < thread_num i++) Threads[i].join ();
    Release socket closesocket (SVR);
    WSACleanup ();
return 0;
 }
Client
ClientUdp.cpp: Defines the entry point for a console application. #include "stdafx.h" #pragma comment (lib, "Ws2_32.lib") #include <Winsock2.h> #include <WS2tcpip.h> #inclu 
    De <stdio.h> #include <string.h> #include <stdlib.h> #include <thread> void new_client (int pos) {
    WORD wversionrequested;
    Wsadata Wsadata;
    int err;
    wversionrequested = Makeword (1, 1);
    Err = WSAStartup (wversionrequested, &wsadata);

    if (Err!= 0) {return;} if (Lobyte (wsadata.wversion)!= 1 | |
        Hibyte (wsadata.wversion)!= 1) {wsacleanup ();
    Return
    Socket Client = socket (af_inet, SOCK_DGRAM, 0);

    Sockaddr_in Server;
    The underlying information to be connected server.sin_family = af_inet;
    Server.sin_port = htons (6002); Inet_pton (Af_inet, "127.0.0.1", &server.sin_addr);
    The dotted decimal address translates into a network byte sequence char recvbuf[128];
    Char sendbuf[128];
    int len = sizeof (SOCKADDR);
        while (true) {printf (' Please input message:\n ');
   gets_s (SENDBUF);     sprintf_s (SendBuf, "%s_%d", SendBuf, POS);

        SendTo (Client, SendBuf, strlen (sendbuf) + 1, 0, (struct sockaddr*) &server, Len);
        Recvfrom (Client, RECVBUF, 128, 0, (struct sockaddr*) &server, &len);
        Char ipserver[16];
        Inet_ntop (Af_inet, &server.sin_addr, Ipserver, sizeof (Ipserver));
    printf ("%s said:%s\n", Ipserver, Recvbuf);
    } closesocket (Client);
WSACleanup ();
    int main () {std::thread threads[10];
    int client_num = 1;

    for (int i = 0; i < client_num i++) threads[i] = Std::thread (new_client, i);

    for (int i = 0; i < client_num i++) Threads[i].join ();
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.