C++ 套接字、多线程和输出处理
C++ Sockets,Multithreading and output handling
我想聊天 system.It 应该写你:然后你输入的任何内容,只要你从其他用户那里得到文本,只需删除你:输入用户:消息和你:再次。
服务器:
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:
其他thread.Thank你有cin换行,貌似不能换行!
我找到答案了!
我注意到当两个线程是 运行 时——一个从 cin 流获取行,另一个正在输出文本,你需要刷新 cout 缓冲区,所以只有文本出现在 std::endl 之后,这会刷新缓冲并同时放入新行所以:
std::cout.flush():
解决了问题:
std::cout << "\b\b\b\b\bUSER:" << buffer << std::endl << "You: ";
std::cout.flush();
我想聊天 system.It 应该写你:然后你输入的任何内容,只要你从其他用户那里得到文本,只需删除你:输入用户:消息和你:再次。
服务器:
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:
其他thread.Thank你有cin换行,貌似不能换行!
我找到答案了! 我注意到当两个线程是 运行 时——一个从 cin 流获取行,另一个正在输出文本,你需要刷新 cout 缓冲区,所以只有文本出现在 std::endl 之后,这会刷新缓冲并同时放入新行所以:
std::cout.flush():
解决了问题:
std::cout << "\b\b\b\b\bUSER:" << buffer << std::endl << "You: ";
std::cout.flush();