Skip to content

Мурашкина: чат сервер для Швецовой - #18

Open
murfel wants to merge 2 commits into
h31:masterfrom
ashvetNmurfel:tcp_chat_server
Open

murfel wants to merge 2 commits into
h31:masterfrom
ashvetNmurfel:tcp_chat_server

Conversation

@murfel

@murfel murfel commented Feb 12, 2019

Copy link
Copy Markdown

No description provided.

Comment thread tcp/server/main.cpp
close();
return;
}
inbuf += std::string(buf, buf + len);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Была просьба не пользоваться возможностями STL в коде, взаимодействующим с сетью. Можно не исправлять.

Comment thread tcp/server/main.cpp

std::string uint32t_to_string(uint32_t uint) {
char * chars = new char[4];
for (int i = 0; i < 4; i++) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Код допустимый, но сложный и запутывающий. Я видел достаточно кода на C++, который использует std::string для хранения данных, но всё же мне кажется, что это не самый лучший подход. Как минимум потому, что string - это семантически строка из символов. Если уж приходится использовать тип данных string для хранения байт, то и называть это нужно byte string, как в Python, и указывать это в названии метода. Ну а лучше использовать более подходящие типы (тот же vector).

Кроме того, сама операция копирования реализована довольно запутанно. Есть готовые функции memcpy и memmove.

Comment thread tcp/server/main.cpp
void push_line(const std::string &str);
};

int g_listen_fd = -1;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не готов сейчас перечитывать код и проверять, во всех ли трассах выполнения программу в эту переменную запишется реальный fd. Мне кажется, есть способы написать код, чтобы подобных вопросов (а всегда ли g_listen_fd будет инициализирован корректным значением?) не возникало.

Comment thread tcp/server/main.cpp
FD_SET(cl->fd(), &wfds);
}

check(select(max_fd + 1, &rfds, &wfds, nullptr, nullptr));

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Имейте в виду, что у select есть определенные недостатки, о которых нужно знать. google://select vs poll vs epoll и man://select#BUGS

Comment thread tcp/server/main.cpp
cl->read();


// std::string line;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для хранения предыдущих версий кода есть история Git-а.

Comment thread tcp/server/main.cpp
int main(int argc, char **argv) {
int port = 80;
if (argc >= 2)
port = atoi(argv[1]);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread tcp/server/main.cpp
void client::read() {
char buf[4096];
ssize_t len = ::recv(fd(), buf, sizeof(buf), 0);
if (len == -1) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А если len равен 0?

Comment thread tcp/server/main.cpp
}

int main(int argc, char **argv) {
int port = 80;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не стоит занимать зарезервированные порты своими приложениями. Они зарезервированы не зря.

Comment thread tcp/server/main.cpp

void client::read() {
char buf[4096];
ssize_t len = ::recv(fd(), buf, sizeof(buf), 0);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для надежности есть смысл выставить флаг MSG_DONTWAIT (или флаг O_NONBLOCK для сокета).

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Описание, почему это важно
https://stackoverflow.com/a/5352634/1993895
Если сокет заблокируется, то мы не сможем обрабатывать других клиентов. К сожалению, в неблокирующих сокетах таких нюансов достаточно много.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants