im trying to make a simple example that accept clients using tcp socket and handle them with select function of winsock.
The problem is that when ever i run the select function it keeps return me the value -1 (error) and WSAGetLastError return the value of 10022.
I cant find out what im doing wrong because the fd_set is setting with the sockets properly and the maximum_sd set to the right value.
#include "stdafx.h"
#include <stdio.h>
#include <thread>
#include <queue>
#include <string.h>
#include <WinSock2.h>
#include <iostream>
#include <Windows.h>
using namespace std;
void SlaveThread(queue<char*>* tasks);
void MasterThread(queue<char*>* tasks);
fd_set readfds;
int max_sd = 0;
deque<SOCKET> socketsQueue;
int nSocketsAmount = 0;
int _tmain(int argc, _TCHAR* argv[])
{
queue<char*>* tasksQueue = new queue<char*>();
FD_ZERO(&readfds);
thread SecondThread(MasterThread,tasksQueue);
thread FirstThread(SlaveThread,tasksQueue);
int nReady;
struct timeval timeout={0, 0};
timeout.tv_sec=10;
timeout.tv_usec=0;
while (true)
{
int i;
nReady = select(max_sd + 1, &readfds, NULL, NULL, &timeout);
for (i=0; i < nSocketsAmount && nReady > 0; i++)
{
SOCKET temp = socketsQueue[i];
if (FD_ISSET(temp, &readfds)) {
char buffer[200];
memset(buffer, 0, 200);
recv(temp, buffer, 200, 0);
tasksQueue->push(buffer);
nReady--;
}
}
}
FirstThread.join();
SecondThread.join();
return 0;
};
void SlaveThread(queue<char*>* tasks)
{
while (true)
{
if (!tasks->empty())
{
cout << tasks->front() << " Queue size : " << tasks->size() << endl;
tasks->pop();
}
Sleep(1000);
}
};
void MasterThread(queue<char*>* tasks)
{
WSAData WinSockData;
WORD Version = MAKEWORD(2, 1);
WSAStartup(Version, &WinSockData);
/* Create socket structure */
SOCKADDR_IN Server;
Server.sin_addr.s_addr = inet_addr("10.0.0.7");
Server.sin_family = AF_INET;
Server.sin_port = htons(27015);
SOCKET ListenSock = socket(AF_INET, SOCK_STREAM, NULL);
SOCKET Connect;
::bind(ListenSock, (SOCKADDR*)&Server, sizeof(Server));
int errno0 = WSAGetLastError();
listen(ListenSock, 1);
int errno1 = WSAGetLastError();
cout << "Listening on port 27015" << endl;
char buffer[200];
int size = sizeof(Server);
while (true)
{
if (Connect = accept(ListenSock, (SOCKADDR*)&Server, &size))
{
cout << "Connection established..." << endl;
FD_SET(Connect, &readfds);
socketsQueue.push_front(Connect);
nSocketsAmount++;
if (Connect > max_sd)
{
max_sd = Connect;
}
}
}
WSACleanup();
};
master thread adding the sockets to the fd_set and sockets queue. and the main use select to get the socket need to read from.
Any suggestions why is that happen?
Thank you.
select
. – Ben Voigt