Winsock select server 与 client 示例代码
参考 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 示例代码的更多相关文章
- python 连接sql server数据库的示例代码
首先,到http://pymssql.sourceforge.net/下载pymssql模块,必须安装这个模块才可以用python连接mysql 以下是sql server的操作代码,需要注意字符集 ...
- swoole 异步非堵塞 server/端 client/端 代码,已经测试完毕。贴代码
服务器环境 centos7.0 swoole4.3 php7.2 pcre4.8 nginx1.8 php-fpm server.php <?php class Server { pr ...
- Winsock网络编程笔记(3)----基于UDP的server和client
在上一篇随笔中,对Winsock中基于tcp面向连接的Server和Client通信进行了说明,但是,Winsock中,Server和Client间还可以通过无连接通信,也就是采用UDP协议.. 因此 ...
- Winsock网络编程笔记(2)----基于TCP的server和client
今天抽空看了一些简单的东西,主要是对服务器server和客户端client的简单实现. 面向连接的server和client,其工作流程如下图所示: 服务器和客户端将按照这个流程就行开发..(个人觉得 ...
- SQL Server中Table字典数据的查询SQL示例代码
SQL Server中Table字典数据的查询SQL示例代码 前言 在数据库系统原理与设计(第3版)教科书中这样写道: 数据库包含4类数据: 1.用户数据 2.元数据 3.索引 4.应用元数据 其中, ...
- redis 学习笔记(2)-client端示例代码
redis提供了几乎所有主流语言的client,java中主要使用二种:Jedis与Redisson 一.Jedis的使用 <dependency> <groupId>redi ...
- C/C++ 开源库及示例代码
C/C++ 开源库及示例代码 Table of Contents 说明 1 综合性的库 2 数据结构 & 算法 2.1 容器 2.1.1 标准容器 2.1.2 Lockfree 的容器 2.1 ...
- Redis简单命令(部分示例代码)
一.redis文件夹下的可执行文件(文章尾部有示例代码) 可执行文件 作用 redis-server 启动redis redis-cli redis命令行工具 redis-benchmark 基准测试 ...
- 基于DotNetOpenAuth的OAuth实现示例代码: 获取access token
1. 场景 根据OAuth 2.0规范,该场景发生于下面的流程图中的(D)(E)节点,根据已经得到的authorization code获取access token. 2. 实现环境 DotNetOp ...
随机推荐
- python——体育竞技
一.体育竞技分析基本规则两个球员,交替用球拍击球发球权,回合未能进行一次击打回合结束首先达到15分赢得比赛 1.自顶向下的设计 #7_game_2.py from random import * de ...
- log4j.properties文件无法解析
普通工程:log4j.properties文件必须放在src根目录下
- 1046 Shortest Distance (20分)
The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed t ...
- openlayers-统计图显示(中国区域高亮)
openlayers版本: v3.19.1-dist 统计图效果: 案例下载地址:https://gitee.com/kawhileonardfans/openlayers-examp ...
- python3(四十)datetime timestamp str
"""时间处理 """ __author__on__ = 'shaozhiqi 2019/9/25' # !/usr/bin/env pyt ...
- php.ini配置文件详解(基于5.2.17版本)
[PHP] ;;;;;;;;;;;;;;;;;;;; About php.ini ;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;; 关于php.ini文件 ;;;;; ...
- Golang中的Gosched、Goexit、GOMAXPROCS
Golang进程权限调度包runtime三大函数Gosched,Goexit,GOMaXPROCS runtime.Gosched(),用于让出CPU时间片,让出当前goroutine的执行权限,调度 ...
- softmax回归推导
向量\(y\)(为one-hot编码,只有一个值为1,其他的值为0)真实类别标签(维度为\(m\),表示有\(m\)类别): \[y=\begin{bmatrix}y_1\\ y_2\\ ...\\y ...
- 【three.js 第一课】创建场景,显示几何体
<!DOCTYPE html> <html> <head> <title>demo1</title> </head> <s ...
- Python—一个简单搜索引擎索引库
因为课业要求,搭建一个简单的搜索引擎,找了一些相关资料并进行了部分优化(坑有点多) 一.数据 数据是网络上爬取的旅游相关的攻略页面 这个是travels表,在索引中主要用到id和url两个字段. 页面 ...