⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bserver.cpp

📁 这个是网络编程
💻 CPP
📖 第 1 页 / 共 2 页
字号:
//
// Sample: Blocking IPv4/IPv6 Server
//
// Files:
//      bserver.cpp     - this file
//      resolve.cpp     - routines for resovling addresses, etc.
//      resolve.h       - header file for resolve.c
//
// Description:
//      This sample illustrates simple blocking IO for TCP and UDP for
//      both IPv4 and IPv6. This sample uses the getaddrinfo/getnameinfo
//      APIs which allows this application to be IP agnostic. That is the
//      desired address family (AF_INET or AF_INET6) can be determined
//      simply from the string address passed via the -l command.
//
//      For TCP, a listening thread is spawned for each available address family.
//      Each thread blocks on an accept call. Once accept completes, two threads
//      are created for each client: a sending thread and a receiving thread.
//      The sending thread sends the requested amount of data while the receive
//      thread read data until the socket is closed.  Each client thread exits
//      once its task is completed. The receiving thread will close the socket 
//      after it has received all the echoed data.
//
//      For UDP, a main thread is spawned for each available address family.
//      Then a receive thread is spawned from there. The main thread then sends
//      the requested data and waits on the receive thread's handle.
//
//      For example:
//          If this sample is called with the following command lines:
//              bserver.exe -l fe80::2efe:1234 -e 5150
//              bserver.exe -l ::
//          Then the server creates an IPv6 socket as an IPv6 address was
//          provided.
//
//          On the other hand, with the following command line:
//              bserver.exe -l 7.7.7.1 -e 5150
//              bserver.exe -l 0.0.0.0
//          Then the server creates an IPv4 socket.
//
// Compile:
//      cl -o bserver.exe bserver.cpp resolve.cpp ws2_32.lib
//
// Usage:
//      bserver.exe [options]
//          -a 4|6     Address family, 4 = IPv4, 6 = IPv6 [default = IPv4]
//          -b size    Size of send/recv buffer in bytes
//          -e port    Port number
//          -l addr    Local address to bind to [default INADDR_ANY for IPv4 or INADDR6_AN
//          -p proto   Which protocol to use [default = TCP]
//             tcp         Use TCP protocol
//             udp         Use UDP protocol
//
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

#include "resolve.h"

#define DEFAULT_BUFFER_SIZE     4096    // default buffer size
#define MAX_LISTEN_SOCKETS      8       // maximum listening sockets

int gAddressFamily = AF_UNSPEC,         // default to unspecified
    gSocketType    = SOCK_STREAM,       // default to TCP socket type
    gProtocol      = IPPROTO_TCP,       // default to TCP protocol
    gBufferSize    = DEFAULT_BUFFER_SIZE;

char *gBindAddr    = NULL,              // local interface to bind to
     *gBindPort    = "5150";            // local port to bind to

struct _BUFFER_OBJ;

//
// Allocated for each client connection
//
typedef struct _CONNECTION_OBJ
{
    SOCKET      s;              // Client socket
    HANDLE      hRecvSema;      // Semaphore incremented for each receive

    struct _BUFFER_OBJ *PendingSendHead,    // List of pending buffers to send
                       *PendingSendTail;    // End of the list

    CRITICAL_SECTION    SendRecvQueueCritSec; // Protect access to this structure

} CONNECTION_OBJ;

//
// Allocated for each receiver posted
//    Each receive thread allocates one of these for a receive operation.
//    After data is read, this object is queued for the send thread to
//    echo back to the client (sender).
//
typedef struct _BUFFER_OBJ
{
    char        *buf;           // Data buffer for data
    int          buflen;        // Length of buffer or number of bytes contained in buffer

    SOCKADDR_STORAGE addr;      // Address data was received from (UDP)
    int              addrlen;   // Length of address

    struct _BUFFER_OBJ *next;
} BUFFER_OBJ;

//
// Statistics counters
//
volatile LONG gBytesRead=0,
              gBytesSent=0,
              gStartTime=0,
              gBytesReadLast=0,
              gBytesSentLast=0,
              gStartTimeLast=0,
              gConnectedClients=0;


//
// Function: usage
//
// Description:
//      Prints usage information and exits the process.
//
void usage(char *progname)
{
    fprintf(stderr, "usage: %s [-a 4|6] [-e port] [-l local-addr] [-p udp|tcp]\n",
            progname);
    fprintf(stderr, "  -a 4|6     Address family, 4 = IPv4, 6 = IPv6 [default = IPv4]\n"
                    "  -b size    Buffer size for send/recv [default = %d]\n"
                    "  -e port    Port number [default = %s]\n"
                    "  -l addr    Local address to bind to [default INADDR_ANY for IPv4 or INADDR6_ANY for IPv6]\n"
                    "  -p tcp|udp Which protocol to use [default = TCP]\n",
                    gBufferSize,
                    gBindPort
                    );
    ExitProcess(-1);
}

//
// Function: GetConnectionObj
//
// Description:
//    This routine allocates a CONNECTION_OBJ structure and initializes its
//    members. For sake of simplicity, this routine allocates a object from
//    the process heap. For better performance, you should modify this to
//    maintain a lookaside list of structures already allocated and freed
//    and only allocate from the heap when necessary.
//
CONNECTION_OBJ *GetConnectionObj(SOCKET s)
{
    CONNECTION_OBJ *newobj=NULL;

    // Allocate the object
    newobj = (CONNECTION_OBJ *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CONNECTION_OBJ));
    if (newobj == NULL)
    {
        printf("GetConnectionObj: HeapAlloc failed: %d\n", WSAGetLastError());
        ExitProcess(-1);
    }
    newobj->s = s;

    // Create the semaphore for signaling the send thread
    newobj->hRecvSema = CreateSemaphore(NULL, 0, 0x0FFFFFFF, NULL);
    if (newobj->hRecvSema == NULL)
    {
        fprintf(stderr, "GetConnectionObj: CreateSemaphore failed: %d\n", GetLastError());
        ExitProcess(-1);
    }

    InitializeCriticalSection(&newobj->SendRecvQueueCritSec);

    return newobj;
}

//
// Function: FreeConnectionObj
//
// Description:
//    This routine frees a CONNECTIN_OBJ. It first frees the critical section.
//    See the comment for GetConnectionObj about using lookaside lists.
//
void FreeConnectionObj(CONNECTION_OBJ *obj)
{
    DeleteCriticalSection(&obj->SendRecvQueueCritSec);
    HeapFree(GetProcessHeap(), 0, obj);
}

//
// Function: GetBufferObj
// 
// Description:
//    Allocate a BUFFER_OBJ. Each receive posted by a receive thread allocates
//    one of these. After the recv is successful, the BUFFER_OBJ is queued for
//    sending by the send thread. Again, lookaside lists may be used to increase
//    performance.
//
BUFFER_OBJ *GetBufferObj(int buflen)
{
    BUFFER_OBJ *newobj=NULL;

    // Allocate the object
    newobj = (BUFFER_OBJ *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BUFFER_OBJ));
    if (newobj == NULL)
    {
        fprintf(stderr, "GetBufferObj: HeapAlloc failed: %d\n", GetLastError());
        ExitProcess(-1);
    }
    // Allocate the buffer
    newobj->buf = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BYTE) *buflen);
    if (newobj->buf == NULL)
    {
        fprintf(stderr, "GetBufferObj: HeapAlloc failed: %d\n", GetLastError());
        ExitProcess(-1);
    }
    newobj->buflen = buflen;

    newobj->addrlen = sizeof(newobj->addr);

    return newobj;
}

//
// Function: FreeBufferObj
// 
// Description:
//    Free the buffer object.
//
void FreeBufferObj(BUFFER_OBJ *obj)
{
    HeapFree(GetProcessHeap(), 0, obj->buf);
    HeapFree(GetProcessHeap(), 0, obj);
}

//
// Function: EnqueueBufferObj
//
// Description:
//   Queue up a receive buffer for this connection. After enqueueing the receiver
//   will release the counting semaphore which will release the sender to 
//   dequeue a buffer and send it.
//
void EnqueueBufferObj(CONNECTION_OBJ *conn, BUFFER_OBJ *obj)
{
    EnterCriticalSection(&conn->SendRecvQueueCritSec);

    if (conn->PendingSendHead == NULL)
    {
        // Queue is empty
        conn->PendingSendHead = conn->PendingSendTail = obj;
    }
    else
    {
        // Put new object at the end 
        conn->PendingSendTail->next = obj;
        conn->PendingSendTail = obj;
    }
    LeaveCriticalSection(&conn->SendRecvQueueCritSec);
}

// 
// Function: DequeueBufferObj
//
// Description:
//    Remove a BUFFER_OBJ from the given connection's queue for sending.
//
BUFFER_OBJ *DequeueBufferObj(CONNECTION_OBJ *conn)
{
    BUFFER_OBJ *ret=NULL;

    EnterCriticalSection(&conn->SendRecvQueueCritSec);

    if (conn->PendingSendTail != NULL)
    {
        // Queue is non empty
        ret = conn->PendingSendHead;

        conn->PendingSendHead = conn->PendingSendHead->next;
        if (conn->PendingSendTail == ret)
        {
            // Item is the only item in the queue
            conn->PendingSendTail = NULL;
        }
    }

    LeaveCriticalSection(&conn->SendRecvQueueCritSec);

    return ret;
}

//
// Function: ValidateArgs
//
// Description:
//      Parses the command line arguments and sets up some global 
//      variables.
//
void ValidateArgs(int argc, char **argv)
{
    int     i;

    for(i=1; i < argc ;i++)
    {
        if (((argv[i][0] != '/') && (argv[i][0] != '-')) || (strlen(argv[i]) < 2))
            usage(argv[0]);
        else
        {
            switch (tolower(argv[i][1]))
            {
                case 'a':               // address family - IPv4 or IPv6
                    if (i+1 >= argc)
                        usage(argv[0]);
                    if (argv[i+1][0] == '4')
                        gAddressFamily = AF_INET;
                    else if (argv[i+1][0] == '6')
                        gAddressFamily = AF_INET6;
                    else
                        usage(argv[0]);
                    i++;
                    break;
                case 'b':               // buffer size for send/recv
                    if (i+1 >= argc)
                        usage(argv[0]);
                    gBufferSize = atol(argv[++i]);
                    break;
                case 'e':               // endpoint - port number
                    if (i+1 >= argc)
                        usage(argv[0]);
                    gBindPort = argv[++i];
                    break;
                case 'l':               // local address for binding
                    if (i+1 >= argc)
                        usage(argv[0]);
                    gBindAddr = argv[++i];
                    break;
                case 'p':               // protocol - TCP or UDP
                    if (i+1 >= argc)
                        usage(argv[0]);
                    if (_strnicmp(argv[i+1], "tcp", 3) == 0)
                    {
                        gProtocol = IPPROTO_TCP;
                        gSocketType = SOCK_STREAM;
                    }
                    else if (_strnicmp(argv[i+1], "udp", 3) == 0)
                    {
                        gProtocol = IPPROTO_UDP;
                        gSocketType = SOCK_DGRAM;
                    }
                    else
                        usage(argv[0]);
                    i++;
                    break;
                default:
                    usage(argv[0]);
                    break;
            }
        }
    }
}

//
// Function: ReceiveThead
//
// Description:
//    One of these threads is started for each client connection.
//    This thread sits in a loop, receiving data. For each receive, the
//    buffer is queued for sending by the SenderThread for this connection.
//
DWORD WINAPI ReceiveThread(LPVOID lpParam)
{
    CONNECTION_OBJ *ConnObj=NULL;
    BUFFER_OBJ     *BuffObj=NULL;
    int             rc;

    // Retrieve the connection object for this connection
    ConnObj = (CONNECTION_OBJ *)lpParam;

    if (gProtocol == IPPROTO_UDP)
    {
        // For UDP all we do is receive packets on the port
        while (1)
        {
            // Allocate the buffer for datagram send/recv
            BuffObj = GetBufferObj(gBufferSize);

            rc = recvfrom(
                    ConnObj->s, 
                    BuffObj->buf, 
                    BuffObj->buflen, 
                    0, 
                    (SOCKADDR *)&BuffObj->addr, 
                   &BuffObj->addrlen);

            BuffObj->buflen = rc;

            if (rc > 0)
            {
                // Increment the statistics
                InterlockedExchangeAdd(&gBytesRead, rc);
                InterlockedExchangeAdd(&gBytesReadLast, rc);
            }

            // Queue the receive buffer for sending and signal the send thread
            EnqueueBufferObj(ConnObj, BuffObj);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -