转:socket select模型示例
生活随笔
收集整理的這篇文章主要介紹了
转:socket select模型示例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
// selectSocketMode.cpp : Defines the entry point for the console application.//
#include "stdafx.h"/*問題:?1.listen(ListenSocket, 5)?是表明這個程序可同時處理5個客戶端接入的請求如果有6個客戶端同時接入請求會發(fā)生什么情況?不知道我的理解對不對?
2.定義LPSOCKET_INFORMATION SocketArray[FD_SETSIZE]; // FD_SETSIZE=64 ?這里能說明程序可以處理64個(讀/寫)請求操作?如果是那么如果有多于64個的請求會發(fā)生什么呢??
3.如何測試這個服務程序的接入能力呢?它能接入多少個客戶端??
4.客戶端的程序如何寫?沒有這方面經驗不知道如何入手,不知大家是怎么測試的??我是剛開始接觸網(wǎng)絡編程,沒有經驗,希望大家能夠踴躍討論幫我解決問題
1、超過則連接的客戶端會收到WSAECONNREFUSED的錯誤,也就是連接被拒絕。 ??
2、如果只定義了SOCKET類型數(shù)組的數(shù)量為64,那多于你就沒變量羅!要不你把第65個覆蓋掉以前的,要不你如果用SocketArrar[64]來保存第65個就會崩掉羅,因為數(shù)組越界了!呵呵! ??
3、寫個各戶端試驗就行了羅! ??
4、我沒仔細看你上面的程序,看你的介紹應該是TCP連接,客戶端你就創(chuàng)建一個SOCKET然后connect到服務端就行了啊!成功后你就可能通過send和recv來和服務器進行通訊了!
SELECT模型并不適合并發(fā)連接比較多的情況。如果是高并發(fā)的情況,推薦使用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套接字異步)的啟動命令// 該函數(shù)的第一個參數(shù)指明程序請求使用的Socket版本// 操作系統(tǒng)利用第二個參數(shù)返回請求的Socket的版本信息if ((Ret = WSAStartup(0x0202,&wsaData)) != 0)?{?printf("WSAStartup() failed with error %d\n", Ret);?WSACleanup();?return;?}?// Prepare a socket to listen for connections. ? ??// 創(chuàng)建一個與指定傳送服務提供者捆綁的套接口if (INVALID_SOCKET == (ListenSocket = WSASocket(AF_INET, // int af 地址族描述。SOCK_STREAM, ? ?// int type 新套接口的類型描述0, ? ? ? ? ? ? ?// int protocol 套接口使用的特定協(xié)議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;?}?// 監(jiān)聽這個端口,這個程序可同時處理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;?// 本函數(shù)可用于任一狀態(tài)的任一套接口。它用于獲取與套接口相關的操作參數(shù),// 而與具體協(xié)議或通訊子系統(tǒng)無關。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--;?}?
#include "stdafx.h"/*問題:?1.listen(ListenSocket, 5)?是表明這個程序可同時處理5個客戶端接入的請求如果有6個客戶端同時接入請求會發(fā)生什么情況?不知道我的理解對不對?
2.定義LPSOCKET_INFORMATION SocketArray[FD_SETSIZE]; // FD_SETSIZE=64 ?這里能說明程序可以處理64個(讀/寫)請求操作?如果是那么如果有多于64個的請求會發(fā)生什么呢??
3.如何測試這個服務程序的接入能力呢?它能接入多少個客戶端??
4.客戶端的程序如何寫?沒有這方面經驗不知道如何入手,不知大家是怎么測試的??我是剛開始接觸網(wǎng)絡編程,沒有經驗,希望大家能夠踴躍討論幫我解決問題
1、超過則連接的客戶端會收到WSAECONNREFUSED的錯誤,也就是連接被拒絕。 ??
2、如果只定義了SOCKET類型數(shù)組的數(shù)量為64,那多于你就沒變量羅!要不你把第65個覆蓋掉以前的,要不你如果用SocketArrar[64]來保存第65個就會崩掉羅,因為數(shù)組越界了!呵呵! ??
3、寫個各戶端試驗就行了羅! ??
4、我沒仔細看你上面的程序,看你的介紹應該是TCP連接,客戶端你就創(chuàng)建一個SOCKET然后connect到服務端就行了啊!成功后你就可能通過send和recv來和服務器進行通訊了!
SELECT模型并不適合并發(fā)連接比較多的情況。如果是高并發(fā)的情況,推薦使用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套接字異步)的啟動命令// 該函數(shù)的第一個參數(shù)指明程序請求使用的Socket版本// 操作系統(tǒng)利用第二個參數(shù)返回請求的Socket的版本信息if ((Ret = WSAStartup(0x0202,&wsaData)) != 0)?{?printf("WSAStartup() failed with error %d\n", Ret);?WSACleanup();?return;?}?// Prepare a socket to listen for connections. ? ??// 創(chuàng)建一個與指定傳送服務提供者捆綁的套接口if (INVALID_SOCKET == (ListenSocket = WSASocket(AF_INET, // int af 地址族描述。SOCK_STREAM, ? ?// int type 新套接口的類型描述0, ? ? ? ? ? ? ?// int protocol 套接口使用的特定協(xié)議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;?}?// 監(jiān)聽這個端口,這個程序可同時處理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;?// 本函數(shù)可用于任一狀態(tài)的任一套接口。它用于獲取與套接口相關的操作參數(shù),// 而與具體協(xié)議或通訊子系統(tǒng)無關。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
總結
以上是生活随笔為你收集整理的转:socket select模型示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 强大js web甘特图制作之甘特图的日历
- 下一篇: 硬盘分区表知识——详解硬盘MBR(转)