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
85
86
87
88
89
90
91
92
93
94
95
96
|
#include <stdio.h>
#include "UserInfo.hpp"
void UserInfo::Handle(bool r, bool w)
{
if(!r)
return;
// this functions create for support any client, not one WantChat client:
if(buf_used >= (int)sizeof(buffer)) {
buf_used = 0;
ignoring = true;
}
if(ignoring) {
//CONSOLE_LOG("Ignore the message, it's so big\n");
ReadAndIgnore();
}
else
ReadAndCheck();
}
void UserInfo::ReadAndIgnore()
{
int rc = read(GetFd(), buffer, sizeof(buffer));
//CONSOLE_LOG("readI return %d bytes\n", rc);
if(rc < 1) {
the_master->CloseSession(this);
return;
}
for(int i = 0; i < rc; i++)
if(buffer[i] == '\n')
{ // stop ignoring!
//CONSOLE_LOG("ReadAndIgnore: find \\n\n");
int rest = rc - i - 1;
if(rest > 0)
memmove(buffer, buffer + i + 1, rest);
buf_used = rest;
ignoring = 0;
CheckLines();
}
}
void UserInfo::ReadAndCheck()
{
int rc = read(GetFd(), buffer+buf_used, sizeof(buffer)-buf_used);
CONSOLE_LOG("readC return %d bytes\n", rc);
if(rc < 1) {
the_master->CloseSession(this);
return;
}
buf_used += rc;
CheckLines();
}
void UserInfo::CheckLines()
{
if(buf_used <= 0)
return;
for(int i = 0; i < buf_used; i++) {
if(buffer[i] == '\n') {
//CONSOLE_LOG("[CheckLines] buffer[i] == \\n i = %d\n", i);
buffer[i] = 0;
if(i > 0 && buffer[i-1] == '\r')
buffer[i-1] = 0;
//CONSOLE_LOG("printed: %s\n", buffer);
the_master->HandleMessage(this, buffer);
int rest = buf_used - i - 1;
memmove(buffer, buffer + i + 1, rest);
buf_used = rest;
//CONSOLE_LOG("[CheckLines] new buf_used = %d\n", buf_used);
CheckLines();
return;
}
}
}
void UserInfo::Send(const char *msg, const char spec_ch)
{
char *tmp_msg = new char[1+strlen(msg)+2]; // for spec_symb + \n
if(spec_ch == USUAL_CHAR)
sprintf(tmp_msg, "%s\n", msg);
else
sprintf(tmp_msg, "%c%s\n", spec_ch, msg);
CONSOLE_LOG("send: %s", tmp_msg);
write(GetFd(), tmp_msg, strlen(tmp_msg));
delete[] tmp_msg;
}
|