1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include "GameProjectClient.h"
ChatPair::ChatPair(int socket){
attribs.socket = new int(socket);
start();
}
void ChatPair::start() {
pthread_create(&attribs.sendThread, NULL, (void * (*) (void *))sendMessage, &attribs);
pthread_create(&attribs.receiveThread, NULL, (void * (*) (void *))receiveMessage, &attribs);
}
void ChatPair::join() {
pthread_join(attribs.receiveThread, NULL);
pthread_join(attribs.sendThread, NULL);
}
void * ChatPair::receiveMessage(void* params) {
char buf[100];
Attribs *attribs = (Attribs *)params;
int *listenSocket = attribs->socket;
while(true){
if(recv(*listenSocket, buf, 100, 0) <= 0){
cerr << "Server not responding" << endl;
break;
}
if(strlen(buf) > 0) cout << "\t Server: " << buf << endl << flush;
}
close(*listenSocket);
pthread_cancel(attribs->sendThread);
}
void * ChatPair::sendMessage(void* params) {
char line[100];
string input;
Attribs *attribs = (Attribs *)params;
int *talkSocket = attribs->socket;
while(true) {
getline(cin, input);
strcpy(line, input.c_str());
if(strlen(line) == 1 && line[0] == 'q') {
cout << "Quit" << endl << flush;
break;
}
else if (send(*talkSocket, line, strlen(line) + 1, 0) < 0) {
cerr << "Error: Cannot send message" << endl;
break;
}
}
close(*talkSocket);
pthread_cancel(attribs->receiveThread);
}
ChatPair::~ChatPair() {
delete attribs.socket;
}
|