I have to concatenate the output of fgets
to an int
(clientid
), and store this in a char[1024]
buffer.
Here's my code:
clientid = rand() % 256;
while(1)
{
cout<<"Client: Enter Data for Client=";
fgets(buffer,MAXSIZE-1,stdin);
if((send(sockfd,buffer,strlen(buffer),0))==-1)
{
cout<<"Failure Sending Message";
close(sockfd);
exit(1);
}
else
{
cout<<"Client:Message being sent:"<<buffer;
num=recv(sockfd,buffer,sizeof(buffer),0);
if(num<=0)
{
cout<<"either connection close or Error";
break;
}
buffer[num]='\0';
cout<<"Client:message received from Server:"<<buffer<<endl;
}
}
close(sockfd);
return 0;
How can I extract the clientid
from the message on the server side?
You can add it to the beginning of the buffer itself. For example if your clientid is 123 then you can send "123:Message" where ":" can act as a separator. This means you should be reading those many numbers ahead in buffer, instead of from the beginning.
snprintf (buffer, sizeof(buffer), "%d:", clientid); // Add the clientid at the beginning before reading
fgets(buffer + strlen (buffer),MAXSIZE-1,stdin);// Move by the len of buffer which contains clientid