- 论坛徽章:
- 0
|
#ifndef MY_CTCPCLIENT
#define MY_CTCPCLIENT
#include sys/types.h>
#include sys/socket.h>
#include netinet/in.h>
#include unistd.h>
class CTcpClient
{
public:
CTcpClient();
int connectServer(const char* hostIP, unsigned short hostPort);
int connectServer(unsigned int hostIP, unsigned short hostPort);
int sendData(void *data, unsigned int length);
int recvData(void *data, unsigned int length);
int closeClient();
private:
int sock_fd;
struct sockaddr_in local_addr;
struct sockaddr_in dest_addr;
};
#endif
#include "CTcpClient.h"
#include stdlib.h>
#include string.h>
#include stdio.h>
#include errno.h>
#include assert.h>
#include arpa/inet.h>
CTcpClient::CTcpClient()
{
memset(&local_addr,0,sizeof(local_addr));
memset(&dest_addr, 0, sizeof(dest_addr));
sock_fd = -1;
}
int CTcpClient::connectServer(const char* serverIP, unsigned short serverPort)
{
dest_addr.sin_family = AF_INET; /* 协议名 */
dest_addr.sin_addr.s_addr = inet_addr(serverIP); /* 自动分配地址 */
dest_addr.sin_port = htons(serverPort); /* 端口号 */
if(sock_fd!=-1)
close(sock_fd);
if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) 0)
{
perror(strerror(errno));
return -1;
}
if(connect(sock_fd, (struct sockaddr*)&dest_addr, sizeof(struct sockaddr)) 0)
{
perror(strerror(errno));
return -1;
}
return 1;
}
int CTcpClient::connectServer(unsigned int serverIP, unsigned short serverPort)
{
dest_addr.sin_family = AF_INET; /* 协议名 */
dest_addr.sin_addr.s_addr =htonl(serverIP); /* 自动分配地址 */
dest_addr.sin_port = htons(serverPort); /* 端口号 */
if(sock_fd!=-1)
close(sock_fd);
if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) 0)
{
perror(strerror(errno));
return -1;
}
if(connect(sock_fd, (struct sockaddr*)&dest_addr, sizeof(struct sockaddr)) 0)
{
perror(strerror(errno));
return -1;
}
return 1;
}
int CTcpClient::sendData(void *data, unsigned int length)
{
int send_len = 0;
if((send_len = send(sock_fd, data, length, 0)) 0 )
{
perror(strerror(errno));
return -1;
}
else
{
return send_len;
}
}
int CTcpClient::recvData(void *data, unsigned int length)
{//接收数据即返回
int rev_len = 0;
if((rev_len = recv(sock_fd, data, length, 0)) 0)
{
perror(strerror(errno));
return -1;
}
else
return rev_len;
}
int CTcpClient::closeClient()
{
if(sock_fd!=-1)
{
close(sock_fd);
sock_fd = -1;
}
return 1;
}
#ifdef DEBUG
int main()
{
unsigned char buffer[1024]={'\n'};
CTcpClient myclient;
myclient.connectServer("192.168.1.198",22082);
while(1)
{
myclient.sendData((void*)"hello server",13);
myclient.recvData(buffer,1024);
printf("client:%s\n",buffer);
sleep(2);
}
}
#endif
g++ -o tcp_c CTcpClient.cpp -Wall -DDEBUG
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/108358/showart_2126428.html |
|