This is a Winsock select() server in C++ (I'm posting in this forum so of course) and I have two problems with it. (title)
1. My select olny returns above 0 when a connect request is recived, the rest of the time it returns -1. So I can olny recive data when another person connects. (Person one connects and sends, but it won't recvive until person 2 connects, and etc.)
2. It will repeat the data over and over again once it is recived.....
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <AzjSock.h>
class socketinfo{
public:
SOCKET sock;
WSABUF DataBuf;
bool isused;
int SendBytes;
int RectBytes;
};
int main(int argc, char *argv[])
{
timeval tv;
tv.tv_sec = 10;
tv.tv_usec = 500000;
char* buff;
WSA2S();
SOCKET server;
server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN sinServer;
memset(&sinServer, 0, sizeof(sinServer));
sinServer.sin_family = AF_INET;
sinServer.sin_addr.s_addr = INADDR_ANY; // Where to start server?
sinServer.sin_port = htons(PORT); // Port
if(bind(server, (LPSOCKADDR)&sinServer, sizeof(sinServer)) == SOCKET_ERROR){ easymsg("Couldn't bind."); }
int numclients = 0;
socketinfo clients[9];
for(int uu = 0; uu<9; uu++){
clients[uu].isused = false;
}
if(listen(server,9)){ easymsg("Listen failed."); }
ioctlsocket(server, FIONBIO, &iMode);
FD_SET Reader;
while (true){
FD_ZERO(&Reader);
FD_SET(server, &Reader);
for(int o = 0; o<numclients; o++)
{
FD_SET(clients[o].sock,&Reader);
}
if(select((clients[numclients].sock+1),&Reader,NULL,NULL,&tv))
{
if(FD_ISSET(server,&Reader))
{
SOCKET ATemp;
if((ATemp = accept(server,NULL,NULL)) != INVALID_SOCKET){
numclients++;
clients[numclients].sock = ATemp;
ioctlsocket(clients[numclients].sock,FIONBIO,&iMode);
clients[numclients].SendBytes = 0;
clients[numclients].RectBytes = 0;
clients[numclients].isused = true;
cout<<"Accepted a client.\nNow up to "<<numclients<<" clients.\n";
}
}
for (int i = 0; i<9; i++)
{
if (clients[i].isused == true)
{
if (FD_ISSET(clients[i].sock, &Reader))
{
clients[i].DataBuf.len = 256;
clients[i].DataBuf.buf = buff;
DWORD Flags;
DWORD Rec;
WSARecv(clients[i].sock, &(clients[i].DataBuf), 1,&Rec, &Flags, NULL, NULL);
char* bob = new char[clients[i].DataBuf.len];
bob = clients[i].DataBuf.buf;
cout<<"Recived: "<<bob<<"\n";
}
}
}
}
Sleep(5);
}
closesocket(server);
WSACleanup();
}