gpt4 book ai didi

C++ 套接字、多线程和输出处理

转载 作者:太空狗 更新时间:2023-10-29 23:14:56 24 4
gpt4 key购买 nike

我想制作聊天系统。它应该写你:然后你输入的任何内容,每当你从其他用户那里收到文本时,只需删除你:输入用户:消息和你:再次。

服务器:

        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);

客户:

    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);

读取数据:

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));
}
}

输出:

服务器:

USER:Hello
USER:How are u doing
Hi
You: You: I am fine
USER:gg
wp
You: You:

客户:

You: Hello
You: How are u doing
USER:Hi
USER:I am fine
gg
You: USER:wp

Wannable 服务器输出:

USER:Hello
USER:How are u doing
You: Hi
You: I am fine
USER:gg
You: wp
You:

Wannable 客户端输出:

You: Hello
You: How are u doing
USER:Hi
USER:I am fine
You: gg
USER:wp
You:

在其他线程中有cin获取换行时,似乎不能输入换行符。谢谢!

最佳答案

我找到答案了!我注意到当两个线程正在运行时——一个从 cin 流中获取行,另一个正在输出文本,你需要刷新 cout 缓冲区,所以只有文本只出现在 std::endl 之后,它刷新缓冲区并放入新的同时行所以:

std::cout.flush():

解决问题:

    std::cout << "\b\b\b\b\bUSER:" << buffer << std::endl << "You: ";
std::cout.flush();

关于C++ 套接字、多线程和输出处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31306562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com