C ++, multithreading and output handling
I want to create a chat system. It should write to you: and then whatever you type, and whenever you receive text from another user, just delete you: enter User: message and You: again.
Server:
std::cin.ignore();
std::thread t1(readData,&acceptedSocket);
do{
memset(buffer,0,sizeof(buffer));
std::cout << "You: ";
std::cin.getline(buffer,255);
n = send(acceptedSocket,buffer,strlen(buffer),0);
}while(n > 0);
Customer:
std::cin.ignore();
std::thread t1(readData,&connectingSocket);
do{
memset(buffer,0,sizeof(buffer));
std::cout << "You: ";
std::cin.getline(buffer,255);
n = send(connectingSocket,buffer,strlen(buffer),0);
}while(n > 0);
ReadData:
void readData(int *socketPointer){
int connectingSocket = *socketPointer;
char buffer[256];
memset(buffer,0,sizeof(buffer));
while(recv(connectingSocket,buffer,255,0)){
std::cout << "\b\b\b\b\bUSER:" << buffer << std::endl << "You: ";
memset(buffer,0,sizeof(buffer));
}
}
Output:
Server:
USER:Hello
USER:How are u doing
Hi
You: You: I am fine
USER:gg
wp
You: You:
Customer:
You: Hello
You: How are u doing
USER:Hi
USER:I am fine
gg
You: USER:wp
Wannable Server Output:
USER:Hello
USER:How are u doing
You: Hi
You: I am fine
USER:gg
You: wp
You:
Wannable Client output:
You: Hello
You: How are u doing
USER:Hi
USER:I am fine
You: gg
USER:wp
You:
It seems that you cannot put a new line character while cin is receiving the line on another thread. Thank!
+3
source to share
1 answer
I found the answer! I noticed that when two streams are started - one gets a line from the cin stream and the other outputs text, you need to flush the cout buffer, so only the text appears only after std :: endl, which flushes the buffer and puts a new one at the same time like so:
std::cout.flush():
Fixed issue:
std::cout << "\b\b\b\b\bUSER:" << buffer << std::endl << "You: ";
std::cout.flush();
0
source to share