windows下对socket的send和recv的超时设置,并附一个简洁明了的socket简单demo
Posted wangshaowei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了windows下对socket的send和recv的超时设置,并附一个简洁明了的socket简单demo相关的知识,希望对你有一定的参考价值。
设置方法
int nNetTimeout=10000;//10秒,
//设置发送超时
setsockopt(m_socket,SOL_SOCKET,SO_SNDTIMEO,(char *)&nNetTimeout,sizeof(int));
//设置接收超时
setsockopt(m_socket,SOL_SOCKET,SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));
服务
1 #include <stdio.h> 2 #include <winsock2.h> 3 4 #pragma comment(lib,"ws2_32.lib") 5 6 int main(int argc, char* argv[]) 7 { 8 //初始化WSA 9 WORD sockVersion = MAKEWORD(2, 2); 10 WSADATA wsaData; 11 if (WSAStartup(sockVersion, &wsaData) != 0) 12 { 13 return 0; 14 } 15 //创建套接字 16 SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 17 if (slisten == INVALID_SOCKET) 18 { 19 printf("socket error !"); 20 return 0; 21 } 22 //绑定IP和端口 23 sockaddr_in sin; 24 sin.sin_family = AF_INET; 25 sin.sin_port = htons(8888); 26 sin.sin_addr.S_un.S_addr = INADDR_ANY; 27 if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) 28 { 29 printf("bind error !"); 30 } 31 //开始监听 32 if (listen(slisten, 5) == SOCKET_ERROR) 33 { 34 printf("listen error !"); 35 return 0; 36 } 37 //循环接收数据 38 SOCKET sClient; 39 sockaddr_in remoteAddr; 40 int nAddrlen = sizeof(remoteAddr); 41 char revData[1024]; 42 while (true) 43 { 44 printf("等待连接... "); 45 sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen); 46 if (sClient == INVALID_SOCKET) 47 { 48 printf("accept error !"); 49 continue; 50 } 51 //接收数据 52 int ret = recv(sClient, revData, 255, 0); 53 if (ret > 0) 54 { 55 revData[ret] = 0x00; 56 printf(revData); 57 } 58 //发送数据 59 const char * sendData = "你好,TCP客户端! "; 60 send(sClient, sendData, strlen(sendData), 0); 61 } 62 closesocket(sClient); 63 closesocket(slisten); 64 WSACleanup(); 65 return 0; 66 }
客户端
#include <winsock2.h> #include <WS2tcpip.h> #include<stdio.h> #include<iostream> #include<cstring> using namespace std; #pragma comment(lib, "ws2_32.lib") int main() { WORD sockVersion = MAKEWORD(2, 2); WSADATA data; if (WSAStartup(sockVersion, &data) != 0) { return 0; } sockaddr_in serAddr; serAddr.sin_family = AF_INET; serAddr.sin_port = htons(8888); inet_pton(AF_INET, "127.0.0.1", &serAddr.sin_addr); while (true) { SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sclient == INVALID_SOCKET) { printf("invalid socket!"); return 0; } if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR) { //连接失败 printf("connect error !"); closesocket(sclient); return 0; } send(sclient, "asd", strlen("asd"), 0); char recData[255]; int ret = recv(sclient, recData, 255, 0); if (ret > 0) { recData[ret] = 0x00; printf(recData); } closesocket(sclient); } WSACleanup(); return 0; }
原文:https://blog.csdn.net/weixinhum/article/details/81742248
以上是关于windows下对socket的send和recv的超时设置,并附一个简洁明了的socket简单demo的主要内容,如果未能解决你的问题,请参考以下文章