I am trying to make a socket program that lets two people chat. I have one thread for sending a message and another for receiving a message. When I use cin, it cuts off the first char that I input.
I've been looking at different threads here about cin and cout being tied and not being very thread safe, but nothing has worked.
Here is my send and receive threads: RECV
char buffer[32];
while(true)
{
memset(&buffer, 0, sizeof(buffer));
unsigned long bytes_recv;
bytes_recv = recv(socketfd, &buffer, sizeof(buffer), 0);
if(bytes_recv == 0)
{
break;
}
for(unsigned long i = 0; i < bytes_recv; i++)
{
buffer[i] = buffer[i] ^ key;
}
printf("Message Received: %s\n", buffer);
}
and Send
char buffer[32];
int conn = 1;
while(true)
{
memset(buffer, 0, sizeof(buffer));
std::cout << "Send a message to host: ";
std::cin.clear();
std::cin.getline(buffer, sizeof(buffer));
std::cout << "StrLen: " << strlen(buffer) << std::endl;
for(unsigned long i = 0; i < strlen(buffer); i++)
{
std::cout << "Char: " << buffer[i] << std::endl;
buffer[i] = key ^ buffer[i];
}
conn = send(socketfd, &buffer, strlen(buffer), 0);
if(conn == -1)
{
break;
}
}
If I type "Hello", the buffer only reads "ello" even from the cin thread.
Aucun commentaire:
Enregistrer un commentaire