转:socket select模型示例

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

#include "stdafx.h"
/*
问题: 
1.listen(ListenSocket, 5) 
是表明这个程序可同时处理5个客户端接入的请求
如果有6个客户端同时接入请求会发生什么情况?不知道我的理解对不对?

2.定义LPSOCKET_INFORMATION SocketArray[FD_SETSIZE]; // FD_SETSIZE=64  
这里能说明程序可以处理64个(读/写)请求操作?
如果是那么如果有多于64个的请求会发生什么呢? 

3.如何测试这个服务程序的接入能力呢?它能接入多少个客户端? 

4.客户端的程序如何写?没有这方面经验不知道如何入手,不知大家是怎么测试的? 
我是刚开始接触网络编程,没有经验,希望大家能够踊跃讨论帮我解决问题

1、超过则连接的客户端会收到WSAECONNREFUSED的错误,也就是连接被拒绝。   

2、如果只定义了SOCKET类型数组的数量为64,那多于你就没变量罗!
要不你把第65个覆盖掉以前的,要不你如果用SocketArrar[64]来保存第65个就会崩掉罗,
因为数组越界了!呵呵!   

3、写个各户端试验就行了罗!   

4、我没仔细看你上面的程序,看你的介绍应该是TCP连接,客户端你就创建一个SOCKET
然后connect到服务端就行了啊!成功后你就可能通过send和recv来和服务器进行通讯了!

SELECT模型并不适合并发连接比较多的情况。如果是高并发的情况,推荐使用Overlap或IOCP.
默认Select是64,少于64的连接用Select是很方便的,你可以自己去改头文件的定义,
如果是连接有几百个以上的话,建议用Overlap或IOCP
*/

// Module Name: select.cpp 
// 
// 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. 
// 
// Compile: // 
// cl -o select select.cpp ws2_32.lib 
// 
// Command Line Options:
// select.exe 
// Note: There are no command line options for this sample. 
// 

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

// 将ws2_32.lib连接到工程,也可以在工程选项中的连接中设置
#pragma comment(lib, "ws2_32.lib") 

#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; 

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

DWORD TotalSockets = 0; 
LPSOCKET_INFORMATION SocketArray[FD_SETSIZE]; 

void main(void) 
    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;     
    
    // WSAStartup即WSA(Windows SocKNDs Asynchronous,
    // Windows套接字异步)的启动命令
    // 该函数的第一个参数指明程序请求使用的Socket版本
    // 操作系统利用第二个参数返回请求的Socket的版本信息
    if ((Ret = WSAStartup(0x0202,&wsaData)) != 0) 
    { 
        printf("WSAStartup() failed with error %d\n", Ret); 
        WSACleanup(); 
        return; 
    } 
    
    // Prepare a socket to listen for connections.     
    // 创建一个与指定传送服务提供者捆绑的套接口
    if (INVALID_SOCKET == (ListenSocket = WSASocket(AF_INET, // int af 地址族描述。
            SOCK_STREAM,    // int type 新套接口的类型描述
            0,              // int protocol 套接口使用的特定协议
            NULL,           // LPPROTOCOL_INFO lpProtocolInfo 一个指向PROTOCOL_INFO结构的指针
            0,              // Group g 套接口组的描述字
            WSA_FLAG_OVERLAPPED)))   // int iFlags 套接口属性描述
    { 
        printf("WSASocket() failed with error %d\n", WSAGetLastError()); 
        return; 
    } 
    
    InternetAddr.sin_family = AF_INET; 
    InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY); 
    InternetAddr.sin_port = htons(PORT); 
    
    // 将socket绑定到一个端口
    if (bind(ListenSocket, (PSOCKADDR) &InternetAddr, sizeof(InternetAddr)) 
        == SOCKET_ERROR) 
    { 
        printf("bind() failed with error %d\n", WSAGetLastError()); 
        return; 
    } 
    
    // 监听这个端口,这个程序可同时处理5个客户端接入的请求
    if (listen(ListenSocket, 5)) 
    { 
        printf("listen() failed with error %d\n", WSAGetLastError()); 
        return; 
    } 
    
    // Change the socket mode on the listening socket from blocking to 
    // non-block so the application will not block waiting for requests.     
    NonBlock = 1; 
    // 本函数可用于任一状态的任一套接口。它用于获取与套接口相关的操作参数,
    // 而与具体协议或通讯子系统无关。FIONBIO:允许或禁止套接口s的非阻塞模式。
    if (ioctlsocket(ListenSocket, FIONBIO, &NonBlock) == SOCKET_ERROR) 
    { 
        printf("ioctlsocket() failed with error %d\n", WSAGetLastError()); 
        return; 
    } 
    
    while(TRUE) 
    { 
        // Prepare the Read and Write socket sets for network I/O notification. 
        FD_ZERO(&ReadSet); // 将set初始化为空集NULL。
        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++) 
        {// FD_SET 向集合添加描述字。
            if (SocketArray[i]->BytesRECV > SocketArray[i]->BytesSEND) 
                FD_SET(SocketArray[i]->Socket, &WriteSet); 
            else 
                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; 
        } 
        
        // Check for arriving connections on the listening socket. 
        // FD_ISSET(int fd, fd_set *set);用来测试描述词组set中相关fd的位是否为真
        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() failed with error %d\n", WSAGetLastError()); 
                    return; 
                } 
                
                if (CreateSocketInformation(AcceptSocket) == FALSE) 
                    return;                     
            }
            else 
            {  
                if (WSAGetLastError() != WSAEWOULDBLOCK) 
                { 
                    printf("accept() failed with error %d\n", WSAGetLastError()); 
                    return; 
                } 
            } 
        } 
        
        // 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; 
                if (WSARecv(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes, 
                    &Flags, NULL, NULL) == SOCKET_ERROR) 
                { 
                    if (WSAGetLastError() != WSAEWOULDBLOCK) 
                    { 
                        printf("WSARecv() failed with error %d\n", WSAGetLastError());                             
                        FreeSocketInformation(i); 
                    }                         
                    continue; 
                }   
                else 
                { 
                    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)) 
            { 
                Total--; 
                
                SocketInfo->DataBuf.buf = SocketInfo->Buffer + SocketInfo->BytesSEND; 
                SocketInfo->DataBuf.len = SocketInfo->BytesRECV - SocketInfo->BytesSEND; 
                
                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); 
                    }                         
                    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 %d\n", s); 

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

    // 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 %d\n", SI->Socket); 

    GlobalFree(SI); 

    // Squash the socket array 
    // 调整SocketArray的位置,填补队列中的空缺
    for (i = Index; i < TotalSockets; i++) 
    { 
        SocketArray[i] = SocketArray[i + 1]; 
    } 

    TotalSockets--; 

  

转载于:https://www.cnblogs.com/zkliuym/archive/2010/04/30/1724742.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值