1 Star 0 Fork 0

杭电码农-NEO / HTTP-Web Server Project

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
TcpServer.hpp 2.82 KB
一键复制 编辑 原始数据 按行查看 历史
#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <cstdio>
#include <strings.h>
#include <cerrno>
#include <cstdlib>
#include <signal.h>
#include <netinet/in.h>
#include <ctype.h>
#include <sys/wait.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <mutex>
#include <thread>
#include <cassert>
#include "log.hpp"
#include <memory>
using namespace std;
#define PORT 8080
#define BACKLOG 8
class TcpServer
{
private:
TcpServer(int port = PORT)
: _port(port)
{
}
TcpServer(const TcpServer &copy) = delete;
public:
static TcpServer *GetInstance(int port = PORT)
{
if (_singleton == nullptr) // 双检查加锁,只有第一次进来时需要加锁,其他情况不用加锁
{
_mtx.lock();
if (_singleton == nullptr) // 第一次调用才创建实例!
{
_singleton = new TcpServer(port);
_singleton->InitServer();
}
_mtx.unlock();
}
return _singleton;
}
void InitServer()
{
Socket();
Bind();
Listen();
}
void Socket()
{
_listensock = socket(AF_INET, SOCK_STREAM, 0);
if (_listensock < 0)
{
logMessage(ERROR, "socket error [%s], [%d]", __FILE__, __LINE__);
exit(1);
}
int opt = 1;
setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); // 设置套接字可以被复用,一旦服务器挂掉,可以立马使用一样的端口号重新启动服务器
logMessage(DEBUG, "socket success [%s], [%d]", __FILE__, __LINE__);
}
void Bind()
{
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(_port);
local.sin_addr.s_addr = INADDR_ANY; // 云服务器不能直接bind公网IP,INADDR_ANY随机绑定本主机IP
if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
{
logMessage(ERROR, "bind error [%s], [%d]", __FILE__, __LINE__);
exit(2);
}
logMessage(DEBUG, "bind success [%s], [%d]", __FILE__, __LINE__);
}
void Listen()
{
if (listen(_listensock, BACKLOG) < 0)
{
logMessage(ERROR, "listen error [%s], [%d]", __FILE__, __LINE__);
exit(3);
}
logMessage(DEBUG, "listen success [%s], [%d]", __FILE__, __LINE__);
}
~TcpServer()
{
if (_listensock >= 0)
close(_listensock);
}
int Sock()
{
return _listensock;
}
private:
int _port;
int _listensock = -1;
static TcpServer *_singleton;
static mutex _mtx;
};
mutex TcpServer::_mtx;
TcpServer *TcpServer::_singleton = nullptr;
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/NEO_kou/http-web-server-project.git
git@gitee.com:NEO_kou/http-web-server-project.git
NEO_kou
http-web-server-project
HTTP-Web Server Project
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891