多连接问题,单个连接已可以接收数据。
--------------------------------------------------------------
// tcpserver.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
#pragma comment(lib,"ws2_32")
#include <stdio.h>
#include "string.h"
int main(int argc, char* argv[])
{
int i = 0;
int ret;
char revData[512]={0};
int listening;
//sockaddr_in remoteAddr;
//int nAddrLen = sizeof(remoteAddr);
//sockaddr_in remoteAddr2;
//int nAddrLen2 = sizeof(remoteAddr2);
int b;
SOCKET socka;
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2, 2);
if(WSAStartup(sockVersion, &wsaData) != 0)
return 0;
SOCKET sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sListen == INVALID_SOCKET)
{
printf("socket error\n");
return 0;
}
u_long ul=1;
ioctlsocket(sListen,FIONBIO,&ul);
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(4500);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if(bind(sListen, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
{
printf(" bind error \n");
closesocket(sListen);
return 0;
}
if((listening = listen(sListen, 5)) == SOCKET_ERROR)
{
printf("listen error\n");
closesocket(sListen);
return 0;
}
fd_set rfd;
fd_set rfd2;
FD_ZERO(&rfd);
FD_SET(sListen,&rfd);
select(sListen+1,&rfd,0,0,0);
if(FD_ISSET(sListen,&rfd))
{
socka =accept(sListen, 0, 0);
//sockb =accept(sListen, 0, 0);这里如此正确?有的资料这样写,但到后面将sockb 加入&rfd后select错误。
//有个代码没用select时是先for 然后s[i] = accept(slisten,NULL,NULL); 然后开线程处理每个连接。
//用当没有连接时,FOR完了就开了I个线程,那S[I]得到的是什么,连接如何建立?
printf("a line\n");
while(1)
{2
FD_ZERO(&rfd2);
FD_SET(socka,&rfd2);
if( (ret = select(0,&rfd2,0,0,0)) ==SOCKET_ERROR)
{
printf("select error\n");
}
if(ret > 0)
{
if(FD_ISSET(socka,&rfd2))
{
memset(revData,0x00,strlen(revData));
b=recv(socka,revData,512,0);
if(b >0)
{
printf("get order: %s \n",revData);
}
}
}
}
}
printf("all close\n");
gets(revData);
closesocket(sListen);
WSACleanup();
return 0;
}
[招生]科锐逆向工程师培训(2024年11月15日实地,远程教学同时开班, 第51期)