I have this code but I only eccepts one client at a time:
#include <iostream>
#include <conio.h>
#include <winsock2.h>
#include <string>
using namespace std;
int main()
{
WSADATA wsadat;
WORD rVersion;
rVersion = MAKEWORD(2,0);
if(WSAStartup(rVersion, &wsadat) != NO_ERROR)
{
cout<<"WSA initialization failed.\n";
WSACleanup();
return 1;
}
//Creating the welcome socket
SOCKET welcome_socket;
welcome_socket = socket(AF_INET, SOCK_STREAM, 0);
if(welcome_socket == INVALID_SOCKET)
{
cout<<"Socket could not be created.\n";
WSACleanup();
return 1;
}
string ipaddress;
int portno;
cout<<"Enter your IP address: ";
cin>>ipaddress;
//ipaddress = "127.0.0.1";
cout<<"Enter the port no.: ";
cin>>portno;
//portno=10000;
SOCKADDR_IN sockaddress;
sockaddress.sin_addr.s_addr = inet_addr(ipaddress.c_str());
sockaddress.sin_port = htons(portno);
sockaddress.sin_family = AF_INET;
if(bind(welcome_socket, (SOCKADDR*)(&sockaddress), sizeof(sockaddress)) == SOCKET_ERROR)
{
cout<<"Attempt to bind failed.\n";
WSACleanup();
return 1;
}
//listen for incoming connection requests on the welcome socket
listen(welcome_socket, 1);
//create a socket for communication by accepting any requests on welcome socket
SOCKET comm_sock;
SOCKADDR_IN clientaddr;
int addresslen = sizeof(clientaddr);
char*Buffer = new char[13];
int turn=0;
char* buf;
buf = new char[50];
char temp;
while(!kbhit())
{
comm_sock = accept(welcome_socket, (SOCKADDR*) &clientaddr, &addresslen);
if(comm_sock != SOCKET_ERROR)
{
cout<<"Connection established with client at: "
<<(int)clientaddr.sin_addr.S_un.S_un_b.s_b1<<"."
<<(int)clientaddr.sin_addr.S_un.S_un_b.s_b2<<"."
<<(int)clientaddr.sin_addr.S_un.S_un_b.s_b3<<"."
<<(int)clientaddr.sin_addr.S_un.S_un_b.s_b4<<endl;
}
while(buf !="exit")
{
if(turn==0)
{
cout<<endl;
//send and receive data;
recv(comm_sock, buf, 50, 0);
if(buf[0]=='e' && buf[1]=='x' && buf[2]=='i' && buf[3]=='t')
return 1;
cout<<"Msg from client: "<<buf<<endl;
cin.get(temp);
turn=1;
}
if(turn==1)
{
cout<<"Enter Message: ";
cin.get(buf,50);
if(buf[0]=='e' && buf[1]=='x' && buf[2]=='i' && buf[3]=='t')
return 1;
send(comm_sock, buf,strlen(buf)+1,0);
turn=0;
}
}
}
WSACleanup();
return 1;
}
I need it to accepts multiple clients and recv messages from all of them and then write it to a file. I have the file writing part covered just not the accepting multiple clients and recieving multiple message.
Thanks....