代码拉取完成,页面将自动刷新
//
// Created by 邓书哲 on 2021/11/25.
// 基于接口的TCP封装 服务器端的实现
//
#include <sys/socket.h>
#include <netinet/in.h>
#include <memory.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <csignal>
class Client_Function {
public:
Client_Function() {}
virtual ~Client_Function() {}
public:
virtual void ClientFunction(int nConnectedSocket) = 0;
};
class TCP_Client {
public:
TCP_Client(Client_Function *pObserver, int nServerPort, const char *strServerIP) {
m_pObserver = pObserver;
m_nServerPort = nServerPort;
int nlength = strlen(strServerIP);
m_strServerIP = new char[nlength + 1];
strcpy(m_strServerIP, strServerIP);
signal(SIGPIPE, sighandler);
}
virtual ~TCP_Client() {
delete[] m_strServerIP;
}
public:
int Run() {
int nClientSocket = ::socket(AF_INET, SOCK_STREAM, 0);
if (-1 == nClientSocket) {
std::cout << "socket error" << std::endl;
return -1;
}
sockaddr_in ServerAddress;
memset(&ServerAddress, 0, sizeof(sockaddr_in));
ServerAddress.sin_family = AF_INET;
if (::inet_pton(AF_INET, m_strServerIP, &ServerAddress.sin_addr) != 1) {
std::cout << "inet_pton error" << std::endl;
::close(nClientSocket);
return -1;
}
ServerAddress.sin_port = htons(m_nServerPort);
int ret = connect(nClientSocket, (sockaddr *) &ServerAddress, sizeof(ServerAddress));
if (ret == -1) {
perror("connect");
::close(nClientSocket);
return -1;
}
if (m_pObserver != NULL) {
m_pObserver->ClientFunction(nClientSocket);
}
::close(nClientSocket);
return 0;
}
static void sighandler(int sig) {
std::cout << "capture signal : " << sig << std::endl;
}
private:
int m_nServerPort;
char *m_strServerIP;
Client_Function *m_pObserver;
};
class My_Client_Function : public Client_Function {
public:
My_Client_Function() {}
virtual ~My_Client_Function() {}
private:
virtual void ClientFunction(int nConnectedSocket) {
while(1) {
std::string command = "";
getline(std::cin, command);
command += "\n";
send(nConnectedSocket, command.c_str(), command.length(), 0);
char res[4096] = "";
recv(nConnectedSocket, res, sizeof(res), 0);
std::cout << res;
}
}
};
int main()
{
My_Client_Function client;
TCP_Client tcpclient(&client, 8888, "127.0.0.1");
tcpclient.Run();
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。