使用使用C语言编写基于语言编写基于TCP协议的协议的Socket通讯程序实例分享通讯程序实例分享
主要介绍了使用C语言编写基于TCP协议的Socket通讯程序实例分享,能够实现包括重新连接与每分钟通信一次
等的功能,需要的朋友可以参考下
tcp客户端示例客户端示例
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
typedef struct _NSS_HEADER
{
unsigned short ProtocolVersion; /* 协议版本信息 */
unsigned short MsgType; /* 消息类型 */
unsigned short TransactionNo; /* 传输编号 */
unsigned short PacketLength; /* 数据包长度,包括Header */
}NSS_HEADER;
int str_echo(int sockfd, unsigned short no)
{
ssize_t readLen;
ssize_t writeLen;
char buf[8];
NSS_HEADER *hdr = (NSS_HEADER*)buf;
memset( hdr, 0, sizeof(NSS_HEADER) );
hdr->TransactionNo = no;
// 写数据
int nWriteLen = 0;
while ( true )
{
writeLen = write(sockfd, &buf[nWriteLen], sizeof(NSS_HEADER)-nWriteLen);
// printf( "write %d/n", writeLen);
if (writeLen < 0 && errno == EINTR)
{
continue;
}
else if ( writeLen < 0 )
{
perror ( "write:" );
return -1;
}
nWriteLen += writeLen;
// 已写完,直接返回
if (nWriteLen >= sizeof(NSS_HEADER) )
{
break;
}
}
printf( "send data successed. trans no: %d/n", no );
// 读数据
int nReadLen = 8;
while ( true )
{
readLen = read(sockfd, buf, nReadLen);
// printf( "read: %d/n", readLen );
if (readLen < 0 && errno == EINTR)
{
continue;
}
else if ( readLen <= 0 )
{
perror( "read:");
return -1;
}
评论0
最新资源