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

📄 asyncserver.cpp

📁 这个是网络编程
💻 CPP
📖 第 1 页 / 共 3 页
字号:
//
// Sample: WSAAsyncSelect IPv4/IPv6 Server
//
// Files:
//      asyncserver.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.
//
//      This sample creates a hidden window on which it will receive the
//      asynchronous socket events. For TCP a listening socket will be
//      created for each available address family and will register for
//      the FD_ACCEPT notification. The window procedure will then process
//      all socket events. When data is ready to be received on a socket
//      the read data will be placed in a pending send queue to be echoed
//      back to the client. When the socket can be written (FD_WRITE),
//      as much of the queued data will be sent. This occurs until all
//      the data on the connection has been echoed.
//
//      For UDP, the setup is similar except that no listening sockets
//      are created. A UDP socket is created for each available address
//      family. Afterwhich datagrams are received and echoed using the
//      same queueing mechanism.
//
//      For example:
//          If this sample is called with the following command lines:
//              asyncserver.exe -l fe80::2efe:1234 -e 5150
//              asyncserver.exe -l ::
//          Then the server creates an IPv6 socket as an IPv6 address was
//          provided.
//
//          On the other hand, with the following command line:
//              asyncserver.exe -l 7.7.7.1 -e 5150
//              asyncserver.exe -l 0.0.0.0
//          Then the server creates an IPv4 socket.
//
// Compile:
//      cl.exe -o asyncserver.exe asyncserver.cpp resolve.cpp ws2_32.lib
//
// Usage:
//      asyncserver.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_ANY for IPv6]
//          -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

// Window message for the socket events
#define WM_SOCKET               (WM_USER + 10)

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

HWND  gWorkerWindow=NULL;       // Window to post socket events to

//
// Allocated for each receiver posted
//
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;   // Links buffer objects together
} BUFFER_OBJ;

//
// Allocated for each socket handle
//
typedef struct _SOCKET_OBJ
{
    SOCKET      s;              // Socket handle
    int         closing;        // Indicates whether the connection is closing

    SOCKADDR_STORAGE addr;      // Used for client's remote address
    int              addrlen;   // Length of the address

    BUFFER_OBJ *pending,        // List of pending buffers to be sent
               *pendingtail;    // Last entry in buffer list

    struct _SOCKET_OBJ *next,   // Used to lick socket objects together
                       *prev;
    CRITICAL_SECTION    SockCritSec;    // Synchronize access to socket object
} SOCKET_OBJ;

SOCKET_OBJ *gSocketList=NULL,           // Linked list of all sockets allocated
           *gSocketListEnd=NULL;        // End of socket list
int         gSocketCount=0;             // Nubmer of socket objects in list
CRITICAL_SECTION gSocketCritSec;        // Syncrhonize access to socket list

//
// Statistics counters
//
volatile LONG gBytesRead=0,
              gBytesSent=0,
              gStartTime=0,
              gBytesReadLast=0,
              gBytesSentLast=0,
              gStartTimeLast=0,
              gCurrentConnections=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    Size of send/recv buffer in bytes [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: 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: GetSocketObj
//
// Description:
//    Allocate a socket object and initialize its members. A socket object is
//    allocated for each socket created (either by socket or accept). The
//    socket objects mantain a list of all buffers received that need to
//    be sent.
//
SOCKET_OBJ *GetSocketObj(SOCKET s)
{
    SOCKET_OBJ  *sockobj=NULL;

    sockobj = (SOCKET_OBJ *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SOCKET_OBJ));
    if (sockobj == NULL)
    {
        fprintf(stderr, "GetSocketObj: HeapAlloc failed: %d\n", GetLastError());
        ExitProcess(-1);
    }

    // Initialize the members
    sockobj->s = s;
    sockobj->addrlen = sizeof(sockobj->addr);

    InitializeCriticalSection(&sockobj->SockCritSec);

    return sockobj;
}

//
// Function: FreeSocketObj
//
// Description:
//    Frees a socket object along with any queued buffer objects.
//
void FreeSocketObj(SOCKET_OBJ *obj)
{
    BUFFER_OBJ  *ptr=NULL,
                *tmp=NULL;

    ptr = obj->pending;
    while (ptr)
    {
        tmp = ptr;
        ptr = ptr->next;

        FreeBufferObj(tmp);
    }

    DeleteCriticalSection(&obj->SockCritSec);

    HeapFree(GetProcessHeap(), 0, obj);
}

//
// Function: InsertSocketObj
//
// Description:
//    Insert a socket object into the list of socket objects.
//
void InsertSocketObj(SOCKET_OBJ *sock)
{
    EnterCriticalSection(&gSocketCritSec);

    sock->next = sock->prev = NULL;
    if (gSocketList == NULL)
    {
        // List is empty
        gSocketList = gSocketListEnd = sock;
    }
    else
    {
        // Non empty; insert at end
        sock->prev = gSocketListEnd;
        gSocketListEnd->next = sock;
        gSocketListEnd = sock;

    }
    gSocketCount++;

    LeaveCriticalSection(&gSocketCritSec);
}

//
// Function: RemoveSocketObj
//
// Description:
//    Remove a socket object from the list of sockets.
//
void RemoveSocketObj(SOCKET_OBJ *sock)
{
    EnterCriticalSection(&gSocketCritSec);

    if (sock->prev)
    {
        sock->prev->next = sock->next;
    }
    if (sock->next)
    {
        sock->next->prev = sock->prev;
    }

    if (gSocketList == sock)
        gSocketList = sock->next;
    if (gSocketListEnd == sock)
        gSocketListEnd = sock->prev;

    gSocketCount--;

    LeaveCriticalSection(&gSocketCritSec);
}

//
// Function: FindSocketObj
//
// Description:
//    Search through the lsit of socket objects for the object matching
//    the socket handle supplied. Return the object if found; NULL otherwise.
//
SOCKET_OBJ *FindSocketObj(SOCKET s)
{
    SOCKET_OBJ *ptr=NULL;

    EnterCriticalSection(&gSocketCritSec);

    ptr = gSocketList;
    while (ptr)
    {
        if (ptr->s == s)
            break;
        ptr = ptr->next;
    }

    LeaveCriticalSection(&gSocketCritSec);

    return ptr;
}

//
// Function: RemoveSocketObjByHandle
//
// Description:
//    Remove the socket object structure from the list of objects that
//    matches the socket handle.
//
void RemoveSocketObjByHandle(SOCKET s)
{
    SOCKET_OBJ *obj;

    obj = FindSocketObj(s);
    if (obj)
    {
        RemoveSocketObj(obj);
    }
    return;
}

//
// Function: EnqueueBufferObj
//
// Description:
//   Queue up a receive buffer for this connection.
//
void EnqueueBufferObj(SOCKET_OBJ *sock, BUFFER_OBJ *obj, BOOL AtHead)
{
    EnterCriticalSection(&sock->SockCritSec);
    if (sock->pending == NULL)
    {

⌨️ 快捷键说明

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