参考 https://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancediomethod5.html

Server

// socket_select_server.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

// Description:
//
//    This sample illustrates how to develop a simple echo server Winsock
//    application using the select() API I/O model. This sample is
//    implemented as a console-style application and simply prints
//    messages when connections are established and removed from the server.
//    The application listens for TCP connections on port 5150 and accepts
//    them as they arrive. When this application receives data from a client,
//    it simply echos (this is why we call it an echo server) the data back in
//    it's original form until the client closes the connection.
//
//    Note: There are no command line options for this sample.
//
// Link to ws2_32.lib

#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#include <shlwapi.h>

#define PORT 5150
#define DATA_BUFSIZE 8192

typedef struct _SOCKET_INFORMATION {
    CHAR Buffer[DATA_BUFSIZE];
    WSABUF DataBuf;
    SOCKET Socket;
    OVERLAPPED Overlapped;
    DWORD BytesSEND;
    DWORD BytesRECV;
} SOCKET_INFORMATION, *LPSOCKET_INFORMATION;

// Prototypes
BOOL CreateSocketInformation(SOCKET s);
void FreeSocketInformation(DWORD Index);

// Global var
DWORD TotalSockets = 0;
LPSOCKET_INFORMATION SocketArray[FD_SETSIZE];

int main(int argc, char **argv)
{
    SOCKET ListenSocket;
    SOCKET AcceptSocket;
    SOCKADDR_IN InternetAddr;
    WSADATA wsaData;
    INT Ret;
    FD_SET WriteSet;
    FD_SET ReadSet;
    DWORD i;
    DWORD Total;
    ULONG NonBlock;
    DWORD Flags;
    DWORD SendBytes;
    DWORD RecvBytes;

if ((Ret = WSAStartup(0x0202, &wsaData)) != 0)
    {
        printf("WSAStartup() failed with error %d\n", Ret);
        WSACleanup();
        return 1;
    }
    else
        printf("WSAStartup() is fine!\n");

// Prepare a socket to listen for connections
    if ((ListenSocket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
    {
        printf("WSASocket() failed with error %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("WSASocket() is OK!\n");

InternetAddr.sin_family = AF_INET;
    InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    InternetAddr.sin_port = htons(PORT);

if (bind(ListenSocket, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR)
    {
        printf("bind() failed with error %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("bind() is OK!\n");

if (listen(ListenSocket, 5))
    {
        printf("listen() failed with error %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("listen() is OK!\n");

// Change the socket mode on the listening socket from blocking to
    // non-block so the application will not block waiting for requests
    NonBlock = 1;
    if (ioctlsocket(ListenSocket, FIONBIO, &NonBlock) == SOCKET_ERROR)
    {
        printf("ioctlsocket() failed with error %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("ioctlsocket() is OK!\n");

int ii = 0;
    while (TRUE)
    {
        printf("%dth loop\n", ii++);
        // Prepare the Read and Write socket sets for network I/O notification
        FD_ZERO(&ReadSet);
        FD_ZERO(&WriteSet);

// Always look for connection attempts
        FD_SET(ListenSocket, &ReadSet);

// Set Read and Write notification for each socket based on the
        // current state the buffer.  If there is data remaining in the
        // buffer then set the Write set otherwise the Read set
        for (i = 0; i < TotalSockets; i++)
            if (PathFileExistsA("c:\\sendsocket") > 0)
            {
                remove("c:\\sendsocket");
                FD_SET(SocketArray[i]->Socket, &WriteSet);
            }
            else
                FD_SET(SocketArray[i]->Socket, &ReadSet);
            /*if (SocketArray[i]->BytesRECV > SocketArray[i]->BytesSEND)
            {
                printf("ljx: FD_SET(SocketArray[i]->Socket, &WriteSet)\n");
                FD_SET(SocketArray[i]->Socket, &WriteSet);
            }
            else
            {
                printf("ljx: FD_SET(SocketArray[i]->Socket, &ReadSet)\n");
                FD_SET(SocketArray[i]->Socket, &ReadSet);
            }*/
                
        if ((Total = select(0, &ReadSet, &WriteSet, NULL, NULL)) == SOCKET_ERROR)
        {
            printf("select() returned with error %d\n", WSAGetLastError());
            return 1;
        }
        else
            printf("select() is OK!\n");

// Check for arriving connections on the listening socket.
        if (FD_ISSET(ListenSocket, &ReadSet))
        {
            Total--;
            if ((AcceptSocket = accept(ListenSocket, NULL, NULL)) != INVALID_SOCKET)
            {
                // Set the accepted socket to non-blocking mode so the server will
                // not get caught in a blocked condition on WSASends
                NonBlock = 1;
                if (ioctlsocket(AcceptSocket, FIONBIO, &NonBlock) == SOCKET_ERROR)
                {
                    printf("ioctlsocket(FIONBIO) failed with error %d\n", WSAGetLastError());
                    return 1;
                }
                else
                    printf("ioctlsocket(FIONBIO) is OK!\n");

if (CreateSocketInformation(AcceptSocket) == FALSE)
                {
                    printf("CreateSocketInformation(AcceptSocket) failed!\n");
                    return 1;
                }
                else
                    printf("CreateSocketInformation() is OK!\n");
            }
            else
            {
                if (WSAGetLastError() != WSAEWOULDBLOCK)
                {
                    printf("accept() failed with error %d\n", WSAGetLastError());
                    return 1;
                }
                else
                    printf("accept() is fine!\n");
            }
        }

// Check each socket for Read and Write notification until the number
        // of sockets in Total is satisfied
        for (i = 0; Total > 0 && i < TotalSockets; i++)
        {
            LPSOCKET_INFORMATION SocketInfo = SocketArray[i];
            // If the ReadSet is marked for this socket then this means data
            // is available to be read on the socket
            if (FD_ISSET(SocketInfo->Socket, &ReadSet))
            {
                Total--;
                SocketInfo->DataBuf.buf = SocketInfo->Buffer;
                SocketInfo->DataBuf.len = DATA_BUFSIZE;

Flags = 0;

printf("Before WSARecv\n");
                if (WSARecv(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes, &Flags, NULL, NULL) == SOCKET_ERROR)
                {
                    printf("After WSARecv\n");
                    if (WSAGetLastError() != WSAEWOULDBLOCK)
                    {
                        printf("WSARecv() failed with error %d\n", WSAGetLastError());
                        FreeSocketInformation(i);
                    }
                    else
                        printf("WSARecv() is OK!\n");
                    continue;
                }
                else
                {
                    printf("After WSARecv\n");
                    SocketInfo->DataBuf.buf[RecvBytes] = 0;
                    printf("ljx: from client: %s, RecvBytes %d\n", SocketInfo->DataBuf.buf, RecvBytes);
                    SocketInfo->BytesRECV = RecvBytes;
                    // If zero bytes are received, this indicates the peer closed the connection.
                    if (RecvBytes == 0)
                    {
                        FreeSocketInformation(i);
                        continue;
                    }
                }

}

// If the WriteSet is marked on this socket then this means the internal
            // data buffers are available for more data
            if (FD_ISSET(SocketInfo->Socket, &WriteSet))
            {
                printf("FD_ISSET(SocketInfo->Socket, &WriteSet)\n");
                Total--;

//SocketInfo->DataBuf.buf = SocketInfo->Buffer + SocketInfo->BytesSEND;
                //SocketInfo->DataBuf.len = SocketInfo->BytesRECV - SocketInfo->BytesSEND;
                char stat[1024] = "state okay, ljx";
                SocketInfo->DataBuf.len = strlen(stat);
                snprintf(SocketInfo->DataBuf.buf, SocketInfo->DataBuf.len, "%s", stat);
                printf("xxx message to send: %s\n", SocketInfo->DataBuf.buf);

if (WSASend(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &SendBytes, 0, NULL, NULL) == SOCKET_ERROR)
                {
                    if (WSAGetLastError() != WSAEWOULDBLOCK)
                    {
                        printf("WSASend() failed with error %d\n", WSAGetLastError());
                        FreeSocketInformation(i);
                    }
                    else
                        printf("WSASend() is OK!\n");

continue;
                }
                else
                {
                    SocketInfo->BytesSEND += SendBytes;
                    if (SocketInfo->BytesSEND == SocketInfo->BytesRECV)
                    {
                        SocketInfo->BytesSEND = 0;
                        SocketInfo->BytesRECV = 0;
                    }
                }
            }
        }
    }
}

BOOL CreateSocketInformation(SOCKET s)
{
    LPSOCKET_INFORMATION SI;

printf("Accepted socket number %lld\n", s);

if ((SI = (LPSOCKET_INFORMATION)GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL)
    {
        printf("GlobalAlloc() failed with error %d\n", GetLastError());
        return FALSE;
    }
    else
        printf("GlobalAlloc() for SOCKET_INFORMATION is OK!\n");

// Prepare SocketInfo structure for use
    SI->Socket = s;
    SI->BytesSEND = 0;
    SI->BytesRECV = 0;

SocketArray[TotalSockets] = SI;
    TotalSockets++;
    return(TRUE);
}

void FreeSocketInformation(DWORD Index)
{
    LPSOCKET_INFORMATION SI = SocketArray[Index];
    DWORD i;

closesocket(SI->Socket);
    printf("Closing socket number %lld\n", SI->Socket);
    GlobalFree(SI);

// Squash the socket array
    for (i = Index; i < TotalSockets; i++)
    {
        SocketArray[i] = SocketArray[i + 1];
    }

TotalSockets--;
}

### Client

// socket_select_client.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

// Description:
//    This sample is the echo client. It connects to the TCP server,
//    sends data, and reads data back from the server.
//
// Command Line Options:
//    client [-p:x] [-s:IP] [-n:x] [-o]
//           -p:x      Remote port to send to
//           -s:IP     Server's IP address or hostname
//           -n:x      Number of times to send message
//           -o        Send messages only; don't receive
//
// Link to ws2_32.lib

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

#define DEFAULT_COUNT       20
#define DEFAULT_PORT        5150
#define DEFAULT_BUFFER      2048
#define DEFAULT_MESSAGE     "\'A test message from client\'"

char  szServer[128],                          // Server to connect to
szMessage[1024];                      // Message to send to sever
int   iPort = DEFAULT_PORT;    // Port on server to connect to
DWORD dwCount = DEFAULT_COUNT; // Number of times to send message
BOOL  bSendOnly = FALSE;

// Send data only; don't receive             
// Function: usage:                                   
// Description: Print usage information and exit
void usage()
{
    printf("Chapter5TestClient: client [-p:x] [-s:IP] [-n:x] [-o]\n\n");
    printf("       -p:x      Remote port to send to\n");
    printf("       -s:IP     Server's IP address or hostname\n");
    printf("       -n:x      Number of times to send message\n");
    printf("       -o        Send messages only; don't receive\n");
    printf("\n");
}

// Function: ValidateArgs
// Description:
//    Parse the command line arguments, and set some global flags
//    to indicate what actions to perform
void ValidateArgs(int argc, char **argv)
{
    int    i;
    for (i = 1; i < argc; i++)
    {
        if ((argv[i][0] == '-') || (argv[i][0] == '/'))
        {
            switch (tolower(argv[i][1]))
            {
            case 'p':        // Remote port
                if (strlen(argv[i]) > 3)
                    iPort = atoi(&argv[i][3]);
                break;
            case 's':       // Server
                if (strlen(argv[i]) > 3)
                    strcpy_s(szServer, sizeof(szServer), &argv[i][3]);
                break;
            case 'n':       // Number of times to send message
                if (strlen(argv[i]) > 3)
                    dwCount = atol(&argv[i][3]);
                break;
            case 'o':       // Only send message; don't receive
                bSendOnly = TRUE;
                break;
            default:
                usage();
                break;
            }
        }
    }
}

// Function: main
// Description:
//    Main thread of execution. Initialize Winsock, parse the
//    command line arguments, create a socket, connect to the
//    server, and then send and receive data.
int main(int argc, char **argv)
{
    WSADATA       wsd;
    SOCKET        sClient;
    char          szBuffer[DEFAULT_BUFFER];
    int           ret, i;
    struct sockaddr_in server;
    struct hostent    *host = NULL;

if (argc < 2)
    {
        usage();
        exit(1);
    }

// Parse the command line and load Winsock
    ValidateArgs(argc, argv);
    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
    {
        printf("Failed to load Winsock library! Error %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("Winsock library loaded successfully!\n");

strcpy_s(szMessage, sizeof(szMessage), DEFAULT_MESSAGE);

// Create the socket, and attempt to connect to the server
    sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sClient == INVALID_SOCKET)
    {
        printf("socket() failed with error code %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("socket() looks fine!\n");

server.sin_family = AF_INET;
    server.sin_port = htons(iPort);
    server.sin_addr.s_addr = inet_addr(szServer);

// If the supplied server address wasn't in the form
    // "aaa.bbb.ccc.ddd" it's a hostname, so try to resolve it
    if (server.sin_addr.s_addr == INADDR_NONE)
    {
        host = gethostbyname(szServer);
        if (host == NULL)
        {
            printf("Unable to resolve server %s\n", szServer);
            return 1;
        }
        else
            printf("The hostname resolved successfully!\n");

CopyMemory(&server.sin_addr, host->h_addr_list[0], host->h_length);
    }

if (connect(sClient, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
    {
        printf("connect() failed with error code %d\n", WSAGetLastError());
        return 1;
    }
    else
        printf("connect() is pretty damn fine!\n");

// Send and receive data
    printf("Sending and receiving data if any...\n");

char message[1024];
    while (TRUE)
    {
        printf("please input your message.\n");
        scanf("%s", message);
        snprintf(szMessage, 1024, "%s", message);
        printf("message to be sent %s\n", szMessage);

if (strstr(szMessage, "get_stat"))
        {
            ret = recv(sClient, szBuffer, DEFAULT_BUFFER, 0);
            if (ret == 0)        // Graceful close
            {
                printf("It is a graceful close!\n");
                break;
            }
            else if (ret == SOCKET_ERROR)
            {
                printf("recv() failed with error code %d\n", WSAGetLastError());
                break;
            }

szBuffer[ret] = '\0';
            printf("recv() is OK. Received %d bytes: %s\n", ret, szBuffer);
            continue;
        }

ret = send(sClient, szMessage, strlen(szMessage), 0);
        if (ret == 0)
            break;
        else if (ret == SOCKET_ERROR)
        {
            printf("send() failed with error code %d\n", WSAGetLastError());
            break;
        }

printf("send() should be fine. Send %d bytes\n", ret);
    }
    // ========================================================

for (i = 0; i < (int)dwCount; i++)
    {
        ret = send(sClient, szMessage, strlen(szMessage), 0);
        if (ret == 0)
            break;
        else if (ret == SOCKET_ERROR)
        {
            printf("send() failed with error code %d\n", WSAGetLastError());
            break;
        }

printf("send() should be fine. Send %d bytes\n", ret);

if (!bSendOnly)

{
            ret = recv(sClient, szBuffer, DEFAULT_BUFFER, 0);
            if (ret == 0)        // Graceful close
            {
                printf("It is a graceful close!\n");
                break;
            }
            else if (ret == SOCKET_ERROR)
            {
                printf("recv() failed with error code %d\n", WSAGetLastError());
                break;
            }

szBuffer[ret] = '\0';
            printf("recv() is OK. Received %d bytes: %s\n", ret, szBuffer);
        }
    }

if (closesocket(sClient) == 0)
        printf("closesocket() is OK!\n");
    else
        printf("closesocket() failed with error code %d\n", WSAGetLastError());

if (WSACleanup() == 0)
        printf("WSACleanup() is fine!\n");
    else
        printf("WSACleanup() failed with error code %d\n", WSAGetLastError());

return 0;
}

Winsock select server 与 client 示例代码的更多相关文章

  1. python 连接sql server数据库的示例代码

    首先,到http://pymssql.sourceforge.net/下载pymssql模块,必须安装这个模块才可以用python连接mysql 以下是sql server的操作代码,需要注意字符集 ...

  2. swoole 异步非堵塞 server/端 client/端 代码,已经测试完毕。贴代码

    服务器环境  centos7.0  swoole4.3 php7.2 pcre4.8  nginx1.8   php-fpm server.php <?php class Server { pr ...

  3. Winsock网络编程笔记(3)----基于UDP的server和client

    在上一篇随笔中,对Winsock中基于tcp面向连接的Server和Client通信进行了说明,但是,Winsock中,Server和Client间还可以通过无连接通信,也就是采用UDP协议.. 因此 ...

  4. Winsock网络编程笔记(2)----基于TCP的server和client

    今天抽空看了一些简单的东西,主要是对服务器server和客户端client的简单实现. 面向连接的server和client,其工作流程如下图所示: 服务器和客户端将按照这个流程就行开发..(个人觉得 ...

  5. SQL Server中Table字典数据的查询SQL示例代码

    SQL Server中Table字典数据的查询SQL示例代码 前言 在数据库系统原理与设计(第3版)教科书中这样写道: 数据库包含4类数据: 1.用户数据 2.元数据 3.索引 4.应用元数据 其中, ...

  6. redis 学习笔记(2)-client端示例代码

    redis提供了几乎所有主流语言的client,java中主要使用二种:Jedis与Redisson 一.Jedis的使用 <dependency> <groupId>redi ...

  7. C/C++ 开源库及示例代码

    C/C++ 开源库及示例代码 Table of Contents 说明 1 综合性的库 2 数据结构 & 算法 2.1 容器 2.1.1 标准容器 2.1.2 Lockfree 的容器 2.1 ...

  8. Redis简单命令(部分示例代码)

    一.redis文件夹下的可执行文件(文章尾部有示例代码) 可执行文件 作用 redis-server 启动redis redis-cli redis命令行工具 redis-benchmark 基准测试 ...

  9. 基于DotNetOpenAuth的OAuth实现示例代码: 获取access token

    1. 场景 根据OAuth 2.0规范,该场景发生于下面的流程图中的(D)(E)节点,根据已经得到的authorization code获取access token. 2. 实现环境 DotNetOp ...

随机推荐

  1. SHTC3温湿度传感器的使用

    1.SHTC3简单说明 SHTC3是一个检测温度.湿度的传感器,可以检测-40℃~125℃的温度范围和0%~100%的湿度范围. SHTC3的工作电压范围为:1.62V~3.6V. SHTC3使用的通 ...

  2. 《Three.js 入门指南》3.1.1 - 基本几何形状 -圆环面(TorusGeometry)

    3.1 基本几何形状 圆环面(TorusGeometry) 构造函数 THREE.TorusGeometry(radius, tube, radialSegments, tubularSegments ...

  3. 掌握使用gitlab ci构建Android包的正确方式

    最近公司在做移动端的项目,自然而然的需要搭建打包的环境.本来计划用Jenkins的,但是发现在gitlab上创建完项目后,提示去配置pipeline,于是决定用gitlab去尝试下,毕竟我觉得Jenk ...

  4. Linux命令后面加 & 的作用

    在命令的后面加一个 & 的作用是,将这个任务放到后台执行.看下面的例子. 输入gedit回车,可以看到,打开了Linux的文本编辑器,但是命令窗口执行不了其他命令了,只有退出文本编辑器才能继续 ...

  5. PTA | 1019 数字黑洞 (20分)

    给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字.一直重复这样做,我们很快会停在有" ...

  6. 一个关于HttpClient的轮子

    由于本文较长,需要耐住性子阅读,另外本文中涉及到的知识点较多,想要深入学习某知识点可以参考其他博客或官网资料.本文也非源码分析文章,示例中的源码大多是伪代码和剪辑过的代码示例,由于该轮子为公司内部使用 ...

  7. JavaScript中||和&&的运算

    一般来讲 && 运算和 | | 运算得到的结果都是 true 和 false ,但是 js 中的有点不太一样.当进行 a&&b 和 a| |b (如 1&&am ...

  8. http的长连接和websocket的区别

    一.什么是http协议 HTTP是一个应用层协议,无状态的,端口号为80.主要的版本有1.0/1.1/2.0.   HTTP/1.* 一次请求-响应,建立一个连接,用完关闭: HTTP/1.1 串行化 ...

  9. JNDI数据源的配置及使用 (2010-11-21 21:16:43)转载▼

    JNDI数据源的配置及使用 (2010-11-21 21:16:43)转载▼ 标签: 杂谈 分类: 数据库 数据源的作用 JDBC操作的步骤: 1. 加载驱动程序 2. 连接数据库 3. 操作数据库 ...

  10. 数据结构和算法(Golang实现)(12)常见数据结构-链表

    链表 讲数据结构就离不开讲链表.因为数据结构是用来组织数据的,如何将一个数据关联到另外一个数据呢?链表可以将数据和数据之间关联起来,从一个数据指向另外一个数据. 一.链表 定义: 链表由一个个数据节点 ...