加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
client.cpp 2.68 KB
一键复制 编辑 原始数据 按行查看 历史
dsd 提交于 2022-01-10 11:26 . delete some unused files
//
// 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;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化