Skip to content

Commit

Permalink
update day15
Browse files Browse the repository at this point in the history
  • Loading branch information
yuesong-feng committed Oct 30, 2022
1 parent 1add0b4 commit 9710356
Show file tree
Hide file tree
Showing 24 changed files with 303 additions and 59 deletions.
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,8 @@ C/C++学习的一个难点在于初学时无法做出实际上的东西,没有

[day14-支持业务逻辑自定义、完善Connection类](https://github.com/yuesong-feng/30dayMakeCppServer/blob/main/day14-支持业务逻辑自定义、完善Connection类.md)

[day15-macOS、FreeBSD支持](https://github.com/yuesong-feng/30dayMakeCppServer/blob/main/day15-macOS、FreeBSD支持.md)
[day15-macOS支持、完善业务逻辑自定义](https://github.com/yuesong-feng/30dayMakeCppServer/blob/main/day15-macOS支持、完善业务逻辑自定义.md)

[day16-完善业务逻辑自定义](https://github.com/yuesong-feng/30dayMakeCppServer/blob/main/blob/main/day16-完善业务逻辑自定义.md)

### todo list

Expand Down
4 changes: 3 additions & 1 deletion code/day15/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
build/
*__pycache__/
.vscode/
.vscode/
.cache/
.DS_store
1 change: 1 addition & 0 deletions code/day15/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ endif()
# Compiler flags.
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Wall -Wextra -std=c++17 -pthread")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-attributes") #TODO: remove
# cmake -DCMAKE_BUILD_TYPE=DEBUG ..
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -ggdb -fno-omit-frame-pointer -fno-optimize-sibling-calls")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fPIC")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fPIC")
Expand Down
5 changes: 3 additions & 2 deletions code/day15/src/Acceptor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,10 @@ Acceptor::~Acceptor() {
void Acceptor::AcceptConnection() {
InetAddress *clnt_addr = new InetAddress();
Socket *clnt_sock = new Socket(sock_->Accept(clnt_addr));
printf("new client fd %d! IP: %s Port: %d\n", clnt_sock->GetFd(), clnt_addr->GetIp(), clnt_addr->GetPort());
clnt_sock->SetNonBlocking(); // 新接受到的连接设置为非阻塞式
new_connection_callback_(clnt_sock);
if(new_connection_callback_){
new_connection_callback_(clnt_sock);
}
delete clnt_addr;
}

Expand Down
20 changes: 19 additions & 1 deletion code/day15/src/Connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,12 @@ void Connection::ReadNonBlocking() {
} else if (bytes_read == 0) { // EOF,客户端断开连接
printf("read EOF, client fd %d disconnected\n", sockfd);
state_ = State::Closed;
Close();
break;
} else {
printf("Other error on client fd %d\n", sockfd);
state_ = State::Closed;
Close();
break;
}
}
Expand Down Expand Up @@ -145,6 +147,16 @@ void Connection::WriteBlocking() {
}
}

void Connection::Send(std::string msg){
SetSendBuffer(msg.c_str());
Write();
}

void Connection::Business(){
Read();
on_message_callback_(this);
}

void Connection::Close() { delete_connectioin_callback_(sock_); }

Connection::State Connection::GetState() { return state_; }
Expand All @@ -159,7 +171,13 @@ void Connection::SetDeleteConnectionCallback(std::function<void(Socket *)> const
}
void Connection::SetOnConnectCallback(std::function<void(Connection *)> const &callback) {
on_connect_callback_ = callback;
channel_->SetReadCallback([this]() { on_connect_callback_(this); });
// channel_->SetReadCallback([this]() { on_connect_callback_(this); });
}

void Connection::SetOnMessageCallback(std::function<void(Connection *)> const &callback) {
on_message_callback_ = callback;
std::function<void()> bus = std::bind(&Connection::Business, this);
channel_->SetReadCallback(bus);
}

void Connection::GetlineSendBuffer() { send_buffer_->Getline(); }
Expand Down
6 changes: 5 additions & 1 deletion code/day15/src/EventLoop.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@

EventLoop::EventLoop() { poller_ = new Poller(); }

EventLoop::~EventLoop() { delete poller_; }
EventLoop::~EventLoop() {
Quit();
delete poller_;
}

void EventLoop::Loop() {
while (!quit_) {
Expand All @@ -28,6 +31,7 @@ void EventLoop::Loop() {
}
}
}
void EventLoop::Quit() { quit_ = true; }

void EventLoop::UpdateChannel(Channel *ch) { poller_->UpdateChannel(ch); }
void EventLoop::DeleteChannel(Channel *ch) { poller_->DeleteChannel(ch); }
24 changes: 19 additions & 5 deletions code/day15/src/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,20 @@
*
*/
#include "Server.h"

#include <unistd.h>

#include <functional>

#include "Acceptor.h"
#include "Connection.h"
#include "EventLoop.h"
#include "Socket.h"
#include "ThreadPool.h"
#include "util.h"
#include "Exception.h"

Server::Server(EventLoop *loop) : main_reactor_(loop), acceptor_(nullptr), thread_pool_(nullptr) {
if(main_reactor_ == nullptr){
throw Exception(ExceptionType::INVALID, "main reactor can't be nullptr!");
}
acceptor_ = new Acceptor(main_reactor_);
std::function<void(Socket *)> cb = std::bind(&Server::NewConnection, this, std::placeholders::_1);
acceptor_->SetNewConnectionCallback(cb);
Expand All @@ -39,18 +40,27 @@ Server::Server(EventLoop *loop) : main_reactor_(loop), acceptor_(nullptr), threa
}

Server::~Server() {
for(EventLoop *each : sub_reactors_){
delete each;
}
delete acceptor_;
delete thread_pool_;
}

void Server::NewConnection(Socket *sock) {
ErrorIf(sock->GetFd() == -1, "new connection error");
if(sock->GetFd() == -1){
throw Exception(ExceptionType::INVALID_SOCKET, "New Connection error, invalid client socket!");
}
// ErrorIf(sock->GetFd() == -1, "new connection error");
uint64_t random = sock->GetFd() % sub_reactors_.size();
Connection *conn = new Connection(sub_reactors_[random], sock);
std::function<void(Socket *)> cb = std::bind(&Server::DeleteConnection, this, std::placeholders::_1);
conn->SetDeleteConnectionCallback(cb);
conn->SetOnConnectCallback(on_connect_callback_);
// conn->SetOnConnectCallback(on_connect_callback_);
conn->SetOnMessageCallback(on_message_callback_);
connections_[sock->GetFd()] = conn;
if(new_connect_callback_)
new_connect_callback_(conn);
}

void Server::DeleteConnection(Socket *sock) {
Expand All @@ -65,3 +75,7 @@ void Server::DeleteConnection(Socket *sock) {
}

void Server::OnConnect(std::function<void(Connection *)> fn) { on_connect_callback_ = std::move(fn); }

void Server::OnMessage(std::function<void(Connection *)> fn) { on_message_callback_ = std::move(fn); }

void Server::NewConnect(std::function<void(Connection *)> fn) { new_connect_callback_ = std::move(fn); }
8 changes: 7 additions & 1 deletion code/day15/src/include/Connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Connection {
public:
enum State {
Invalid = 1,
Handshaking,
Connecting,
Connected,
Closed,
Failed,
Expand All @@ -32,9 +32,13 @@ class Connection {

void Read();
void Write();
void Send(std::string msg);

void SetDeleteConnectionCallback(std::function<void(Socket *)> const &callback);
void SetOnConnectCallback(std::function<void(Connection *)> const &callback);
void SetOnMessageCallback(std::function<void(Connection *)> const &callback);
void Business();

State GetState();
void Close();
void SetSendBuffer(const char *str);
Expand All @@ -46,6 +50,7 @@ class Connection {
Socket *GetSocket();

void OnConnect(std::function<void()> fn);
void OnMessage(std::function<void()> fn);

private:
EventLoop *loop_;
Expand All @@ -57,6 +62,7 @@ class Connection {
std::function<void(Socket *)> delete_connectioin_callback_;

std::function<void(Connection *)> on_connect_callback_;
std::function<void(Connection *)> on_message_callback_;

void ReadNonBlocking();
void WriteNonBlocking();
Expand Down
1 change: 1 addition & 0 deletions code/day15/src/include/EventLoop.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class EventLoop {
void Loop();
void UpdateChannel(Channel *ch);
void DeleteChannel(Channel *ch);
void Quit();

private:
Poller *poller_{nullptr};
Expand Down
46 changes: 46 additions & 0 deletions code/day15/src/include/Exception.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* @file Exception.h
* @author 冯岳松 ([email protected])
* @brief
* @version 0.1
* @date 2022-02-07
*
* @copyright Copyright (冯岳松) 2022
*
*/
#pragma once
#include <iostream>
#include <stdexcept>
#include <string>

enum ExceptionType {
INVALID = 0,
INVALID_SOCKET = 1,
};

class Exception : public std::runtime_error {
public:
explicit Exception(const std::string &message) : std::runtime_error(message), type_(ExceptionType::INVALID) {
std::string exception_message = "Message :: " + message + "\n";
std::cerr << exception_message;
}

Exception(ExceptionType type, const std::string &message) : std::runtime_error(message), type_(type) {
std::string exception_message =
"Exception Type :: " + ExceptionTypeToString(type_) + "\nMessage :: " + message + "\n";
std::cerr << exception_message;
}
static std::string ExceptionTypeToString(ExceptionType type) {
switch (type) {
case ExceptionType::INVALID:
return "Invalid";
case ExceptionType::INVALID_SOCKET:
return "Invalid socket";
default:
return "Unknoen";
}
}

private:
ExceptionType type_;
};
28 changes: 28 additions & 0 deletions code/day15/src/include/Log.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @file Log.h
* @author 冯岳松 ([email protected])
* @brief
* @version 0.1
* @date 2022-02-07
*
* @copyright Copyright (冯岳松) 2022
*
*/
#pragma once
class Log
{
private:
/* data */
public:
Log(/* args */);
~Log();
};

Log::Log(/* args */)
{
}

Log::~Log()
{
}

4 changes: 4 additions & 0 deletions code/day15/src/include/Server.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class Server {
std::vector<EventLoop *> sub_reactors_;
ThreadPool *thread_pool_;
std::function<void(Connection *)> on_connect_callback_;
std::function<void(Connection *)> on_message_callback_;
std::function<void(Connection *)> new_connect_callback_;

public:
explicit Server(EventLoop *loop);
Expand All @@ -37,4 +39,6 @@ class Server {
void NewConnection(Socket *sock);
void DeleteConnection(Socket *sock);
void OnConnect(std::function<void(Connection *)> fn);
void OnMessage(std::function<void(Connection *)> fn);
void NewConnect(std::function<void(Connection *)> fn);
};
26 changes: 26 additions & 0 deletions code/day15/src/include/SignalHandler.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @file Signal.h
* @author 冯岳松 ([email protected])
* @brief
* @version 0.1
* @date 2022-02-07
*
* @copyright Copyright (冯岳松) 2022
*
*/
#pragma once
#include <signal.h>
#include <functional>
#include <map>

std::map<int, std::function<void()>> handlers_;
void signal_handler(int sig) {
handlers_[sig]();
}

struct Signal {
static void signal(int sig, const std::function<void()> &handler) {
handlers_[sig] = handler;
::signal(sig, signal_handler);
}
};
2 changes: 1 addition & 1 deletion code/day15/src/include/ThreadPool.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class ThreadPool {
std::queue<std::function<void()>> tasks_;
std::mutex queue_mutex_;
std::condition_variable condition_variable_;
bool stop_{false};
std::atomic<bool> stop_{false};
};

// 不能放在cpp文件,C++编译器不支持模版的分离编译
Expand Down
6 changes: 6 additions & 0 deletions code/day15/src/include/pine.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#include "Server.h"
#include "Buffer.h"
#include "Connection.h"
#include "EventLoop.h"
#include "Socket.h"
#include "SignalHandler.h"
24 changes: 24 additions & 0 deletions code/day15/test/chat_client.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include <Connection.h>
#include <Socket.h>
#include <iostream>

int main() {
Socket *sock = new Socket();
sock->Connect("127.0.0.1", 1234);

Connection *conn = new Connection(nullptr, sock);
while(true){
conn->Read();
std::cout << "Message from server: " << conn->ReadBuffer() << std::endl;
}
// conn->Read();

// if (conn->GetState() == Connection::State::Connected) {
// std::cout << conn->ReadBuffer() << std::endl;
//}
//conn->SetSendBuffer("Hello server!");
//conn->Write();

delete conn;
return 0;
}
Loading

0 comments on commit 9710356

Please sign in to comment.