Hello, I have a problem with my program. I wanted it to have two threads, one of them listening for connections, and the other one receiving data from them... Unfortunately, it acts strangely. It will ignore my cout and cin usage everywhere in the code, so I can't even debug it. May I ask that someone sheds some light on it? Thank you in advance.
#include <windows.h>
#include <iostream.h>
#include <string.h>
#include <cstdlib>
int ConnectionNum, Port=4673;
WSADATA wsaData;
SOCKET Connections[256];
DWORD WINAPI ReceiveThread(LPVOID iValue)
{
//this is going to be receiving TCP/IP packets, as soon as the connection works
}
DWORD WINAPI ListenThread(LPVOID iValue) //this thread is supposed to listen for new connections and store them in an array
{
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int ClientAddrLen;
WSAStartup(MAKEWORD(2,2), &wsaData);
ListeningSocket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ServerAddr.sin_family=AF_INET;
ServerAddr.sin_port=htons(Port);
ServerAddr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(ListeningSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr));
if(listen(ListeningSocket, 5)!=0)
{
cout << "Could not begin listening for connections.";
return 0;
}
ConnectionNum=0;
while(ConnectionNum<256)
{
Connections[ConnectionNum]=accept(ListeningSocket, (SOCKADDR*)&ClientAddr, &ClientAddrLen);
ConnectionNum++;
cout << "New connection.";
}
}
int main()
{
HANDLE hThread1,hThread2;
DWORD dwGenericThread;
char lszThreadParam[3];
hThread1=CreateThread(NULL, 0, ListenThread, &lszThreadParam, 0, &dwGenericThread);
if(hThread1==NULL)
{
DWORD dwError=GetLastError();
cout<<"SCM:Error in Creating thread"<<dwError<<endl ;
return 0;
}
hThread2=CreateThread(NULL, 0, ReceiveThread, &lszThreadParam, 0, &dwGenericThread);
if(hThread2==NULL)
{
DWORD dwError=GetLastError();
cout<<"SCM:Error in Creating thread"<<dwError<<endl ;
return 0;
}
system("pause"); //to keep the entire program from ending
}