1. TcpServer.h
#ifndef TCP_SERVER_H
#define TCP_SERVER_H
#include <thread>
class TcpServer
{
public:
TcpServer(const int port);
~TcpServer();
int Initialize();
int Start();
private:
void Process();
private:
int m_fd;
int m_port;
std::thread *t;
};
#endif // TCP_SERVER_H
2. TcpServer.cpp
#include "TcpServer.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <thread>
TcpServer::TcpServer(const int port):
m_fd(-1),
m_port(port)
{
}
TcpServer::~TcpServer()
{
if(t->joinable())
{
t->join();
t = nullptr;
}
close(m_fd);
}
int TcpServer::Initialize()
{
m_fd = ::socket(AF_INET, SOCK_STREAM, 0);
if( m_fd == -1 )
return -1;
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(m_port);
int flag = 1;
socklen_t len = sizeof(flag);
if(::setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &flag, len) < 0)
{
return -4;
}
if( ::bind(m_fd, (struct sockaddr *)&sin, sizeof(sin)) < 0 )
{
return -2;
}
if( ::listen(m_fd, 10) < 0)
{
return -3;
}
return 0;
}
int TcpServer::Start()
{
// thread accept
t = new std::thread(&TcpServer::Process,this);
return 0;
}
void TcpServer::Process()
{
printf("process...
");
while(true)
{
struct sockaddr_in client;
socklen_t len = sizeof(client);
int sockfd = ::accept(m_fd, (struct sockaddr*)&client, &len );
if(sockfd < 0){
return;
}
/* 提取客户端IP地址 */
char szIP[64] = { 0 }; // 客户端IP地址
std::string strIP = inet_ntop(AF_INET, &client.sin_addr, szIP, sizeof(szIP));
printf("connect from client: %s
", strIP.c_str());
char msg[4096];
int length = read(sockfd, msg, sizeof(msg) - 1);
if( length <= 0 )
{
printf("some error happen when read
");
return ;
}
printf("%s",msg);
if(strcmp(msg,"get stats") != 0)
{
// return;
}
// {'stat':'1', 'version':'${project.name}-V${project.version}-B${SVN.revision}' }
char reply_msg[4096] = "{'stat':'1', 'version':'middleware-V1.0.0-B12965'}";
write(sockfd, reply_msg, strlen(reply_msg) );
close(sockfd);
printf("close
");
}
}
3. main.cpp
#include "TcpServer.h"
#include <unistd.h>
#include <memory>
#include <iostream>
using namespace std;
int main()
{
shared_ptr<TcpServer> spServer = make_shared<TcpServer>(7773);
int ret = 0;
ret = spServer->Initialize();
if (ret != 0){
std::cout<<"initialize failed "<<ret<<std::endl;
}
spServer->Start();
// while(true)
// {
// sleep(1);
// }
return 0;
}
4. telnet
[root@thor ~]# telnet 127.0.0.1 7773
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
get stats
{'stat':'1', 'version':'middleware-V1.0.0-B12965'}Connection closed by foreign host.