-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTcpChatHandler.cpp
More file actions
84 lines (71 loc) · 1.74 KB
/
TcpChatHandler.cpp
File metadata and controls
84 lines (71 loc) · 1.74 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* =====================================================================================
*
* Filename: TcpChatHandler.cpp
*
* Description: Handler for Simple Chat
*
* Version: 1.0
* Created: 04/09/17 13:50:02
* Revision: 0.1 - Creation
* Compiler: g++
*
* Author: Feng Jie<[email protected]>
*
* =====================================================================================
*/
// OS related headers
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
// C standard lib
#include <stdio.h>
#include <stdlib.h>
// C++ standard lib
#include <iostream>
#include <set>
// Self defined
#include "TcpChatHandler.h"
#include "Message.h"
TcpChatHandler::TcpChatHandler()
{
}
TcpChatHandler::~TcpChatHandler()
{
}
bool TcpChatHandler::preHandle(int sock)
{
AutoMutex _l(mLock);
clients.insert(sock);
return true;
}
bool TcpChatHandler::handle(int sock)
{
ssize_t ret;
std::set<int>::iterator it;
while (1) {
if ((ret = recv(sock, this->mRecvBuf, MAX_BUF_SIZE, 0)) <= 0) {
perror("recv failed");
return false;
}
this->mRecvBuf[ret] = 0;
std::cout << "[" << pthread_self() << "]: " << this->mRecvBuf << std::endl;
mLock.lock();
for (it = this->clients.begin(); it != this->clients.end(); ++it) {
if (sock != *it) {
if ((ret = send(*it, this->mRecvBuf, ret, 0)) == -1) {
perror("send failed");
mLock.unlock();
return false;
}
}
}
mLock.unlock();
}
return true;
}
void TcpChatHandler::postHandle(int sock) throw()
{
close(sock);
}