代码拉取完成,页面将自动刷新
#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 ©) = 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;
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。