77 lines
2.1 KiB
C++
77 lines
2.1 KiB
C++
|
#include "reactor.hpp"
|
||
|
#include "fd_event.hpp"
|
||
|
#include "logger.hpp"
|
||
|
#include <cstring>
|
||
|
#include <iostream>
|
||
|
#include <sys/socket.h>
|
||
|
#include <netinet/in.h>
|
||
|
#include <arpa/inet.h>
|
||
|
#include <unistd.h>
|
||
|
#include <thread>
|
||
|
using namespace tinyrpc;
|
||
|
using namespace std;
|
||
|
|
||
|
Reactor reactor;
|
||
|
|
||
|
int main() {
|
||
|
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
|
||
|
sockaddr_in addr{};
|
||
|
addr.sin_family = AF_INET;
|
||
|
addr.sin_addr.s_addr = INADDR_ANY;
|
||
|
addr.sin_port = htons(9001);
|
||
|
|
||
|
int ret = bind(listenfd, (sockaddr*)&addr, sizeof addr);
|
||
|
if(ret == -1) {
|
||
|
logger() << "bind ret -1 err:" << strerror(errno);
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
listen(listenfd, 5);
|
||
|
|
||
|
FdEvent fe(listenfd);
|
||
|
fe.addListenEvent(IOEvent::READ);
|
||
|
fe.setReadCallback([listenfd] {
|
||
|
thread t([listenfd]{
|
||
|
sockaddr_in addr;
|
||
|
socklen_t len = sizeof addr;
|
||
|
int fd = accept(listenfd,(sockaddr*)(&addr), &len);
|
||
|
char ip[32]{};
|
||
|
inet_ntop(AF_INET, &addr.sin_addr, ip, sizeof ip);
|
||
|
logger() << "ip: " << ip << ", port: " << ntohs(addr.sin_port);
|
||
|
// close(fd);
|
||
|
FdEvent* cli = new FdEvent(fd);
|
||
|
cli->addListenEvent(IOEvent::READ);
|
||
|
cli->setNonblock();
|
||
|
cli->setReadCallback([fd, cli] {
|
||
|
char buf[64]{};
|
||
|
int ret = read(fd, buf, 64);
|
||
|
if(ret == 0) {
|
||
|
close(fd);
|
||
|
reactor.delFdEvent(cli);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
cout << buf << endl;
|
||
|
write(fd, buf, ret);
|
||
|
|
||
|
});
|
||
|
logger() << "addFdEvent" << cli->getFd();
|
||
|
reactor.addFdEvent(cli);
|
||
|
}
|
||
|
|
||
|
);
|
||
|
|
||
|
t.join();
|
||
|
});
|
||
|
cout << "listenfd" << listenfd << endl;
|
||
|
reactor.addFdEvent(&fe);
|
||
|
|
||
|
reactor.loop();
|
||
|
// socklen_t len = sizeof addr;
|
||
|
// int fd = accept(listenfd,(sockaddr*)(&addr), &len);
|
||
|
// char ip[32]{};
|
||
|
// inet_ntop(AF_INET, &addr.sin_addr, ip, sizeof ip);
|
||
|
// logger() << "ip: " << ip << ", port: " << ntohs(addr.sin_port);
|
||
|
|
||
|
close(listenfd);
|
||
|
}
|