基于TCP通信源代码如下:
头文件tcp.h
#ifndef TCP_H_
#define TCP_H_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define SERVER 1
#define CLIENT 0
typedef struct _net_tcp
{
int fd; //通信套接字,用于通信
int sockfd;
}NET_TCP;
NET_TCP *tcpCreate( char IP[], int port, int isSerClint);
int tcpSend(NET_TCP *pTcp, unsigned char *pData, int dataLen, int sendLenOneTime);
int tcpRecv(NET_TCP *pTcp, unsigned char *pData, int recvLen);
int tcpClose(NET_TCP *pTcp);
#endif
功能 封装 tcp.c
#include "tcp.h"
NET_TCP *tcpCreate( char IP[], int port, int isSerClint)
{
int fd = 0;
NET_TCP *pTcp = NULL;
pTcp = (NET_TCP *)malloc(sizeof(NET_TCP));
if(NULL == pTcp)
{
printf("%s, pTcp malloc failed.\n", __FUNCTION__);
return NULL;
}
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd < 0)
{
printf("%s, tcp socket failed.\n", __FUNCTION__);
free(pTcp);
pTcp = NULL;
return NULL;
}
struct sockaddr_in addr;
int addrLen = sizeof(addr);
addr.sin_port = htons(port);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(IP);
if( SERVER == isSerClint)
{
printf("server:\n");
if(bind(fd, (struct sockaddr *)&addr, addrLen) < 0)
{
perror("tcp SERVER bind failed.\n");
free(pTcp);
pTcp = NULL;
return NULL;
}
if(listen(fd, 5) < 0)
{
perror("tcp SERVER listen failed.\n");
free(pTcp);
pTcp = NULL;
return NULL;
}
int connfd = 0;
struct sockaddr_in clntAddr;
int clntAddrLen = sizeof(clntAddr);
printf("waiting connect...\n");
connfd = accept(fd, (struct sockaddr *)&clntAddr, &clntAddrLen);
if(connfd < 0)
{
perror("tcp SERVER accept failed.\n");
free(pTcp);
pTcp = NULL;
return NULL;
}
else
{
printf("IP:%s-fd:%d connect to SERVER.\n", inet_ntoa(clntAddr.sin_addr), connfd);
}
pTcp->sockfd = fd;
pTcp->fd = connfd;
}
if( CLIENT == isSerClint)
{
if(connect(fd, (struct sockaddr *)&addr, addrLen) < 0)
{
perror("tcp CLIENT connect failed.\n");
free(pTcp);
pTcp = NULL;
return NULL;
}
pTcp->fd = fd;
pTcp->sockfd = fd;
}
return pTcp;
}
int tcpSend(NET_TCP *pTcp, unsigned char *pData, int dataLen, int sendLenOneTime)
{
int lenIndex = 0;
int ret = 0;
while(1)
{
if( dataLen > sendLenOneTime)
{
ret = send( pTcp->fd, pData + lenIndex, sendLenOneTime, 0);
if(ret < 0)
{
printf("%s, tcp send failed.\n", __FUNCTION__);
break;
}
else
{
dataLen -= sendLenOneTime;
lenIndex += sendLenOneTime;
}
}
else
{
send( pTcp->fd, pData + lenIndex, dataLen, sendLenOneTime);
break;
}
}
return dataLen;
}
int tcpRecv(NET_TCP *pTcp, unsigned char *pData, int recvLen)
{
return recv( pTcp->fd, pData, recvLen, 0);
}
int tcpClose(NET_TCP *pTcp)
{
if(pTcp->sockfd != -1)
{
close(pTcp->sockfd);
}
free(pTcp);
pTcp = NULL;
return 0;
}