通用的Makefile编写与简单的TCP Client
一、TCP Client
TcpClient.h
#pragma once
#include <stdint.h>
class TcpClient
{
public:
bool Connect(const char* pServerAddr,uint16_t nPort);
void SenMsg(const char* pMsg);
private:
int m_cliSocket;;
};
TcpClient.cpp
#include "TcpClient.h"
#include <iostream>
#include <chrono>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;
#define BUFFER_LENGTH 2000
bool TcpClient::Connect(const char* pServerAddr, uint16_t nPort)
{
int error;
struct sockaddr_in svrAddr;
memset(&svrAddr, 0, sizeof(svrAddr));
//创建套接字
m_cliSocket = socket(AF_INET, SOCK_STREAM, 0);
if (m_cliSocket == -1)
{
cout << "Invalid socket" << endl;
exit(1);
}
//设置地址
svrAddr.sin_addr.s_addr = inet_addr(pServerAddr);
svrAddr.sin_family = AF_INET;
svrAddr.sin_port = htons(nPort);
//连接服务器
error = connect(m_cliSocket, (struct sockaddr*) & svrAddr, sizeof(svrAddr));
if (error == -1)
{
cout << "Connect faild:" << strerror(errno) << endl;
exit(1);
}
cout << "Connect successed!" << endl;
return true;
}
void TcpClient::SenMsg(const char* pMsg)
{
//发送信息给服务端
cout << "SenMsg:" << pMsg << endl;
send(m_cliSocket, pMsg, strlen(pMsg)+1, 0);
//关闭套接字
close(m_cliSocket);
}
main.cpp
#include "TcpClient.h"
#include <stdlib.h>
int main(int argc, char** argv)
{
const char* pServerAddr = "127.0.0.1";
uint16_t nPort = 6000;
const char* pMsg = "hello server";
if (argc >= 4)
{
pServerAddr = argv[1];
nPort = (uint16_t)atoi(argv[2]);
pMsg = argv[3];
}
TcpClient client;
if (client.Connect(pServerAddr, nPort))
{
client.SenMsg(pMsg);
}
return 0;
}
二、Makefile
CC = g++ -std=c++11
OPT_LEVEL := -O2
RM = rm -rf
BIN_NAME = Client
OBJS = main.o TcpClient.o
INC_DIRS = -I./
OS_DEFS = -DNDEBUG
LIBS =
CPP_DEPS = main.d TcpClient.d
all: ${BIN_NAME}
${BIN_NAME}: ${OBJS}
${CC} ${OBJS} $(LIBS) -o $@
%.o:%.cpp
$(CC) $(INC_DIRS) $(OS_DEFS) $(OPT_LEVEL) -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
-include $(CPP_DEPS)
clean:
-$(RM) $(OBJS) $(CPP_DEPS) $(BIN_NAME)
三、编译与运行结果
1、文件结构:
2、编译结果:
3、开启之前的TCP Server:./Server 6000
4、开启测试:./Client 127.0.0.1 6000 hello
5、测试结果如下:
6、批量测试脚本:
#!/bin/bash
for((i=0;i<$1;i++))
do
nohup ./Client 127.0.0.1 6000 "hello this is a client" >> /dev/null 2>&1 &
done
循环执行10次:./Client.sh 10
执行结果如下: