加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
tcp_cli.c 1.88 KB
一键复制 编辑 原始数据 按行查看 历史
zcy 提交于 2017-12-16 19:20 . q
#include "tcp_cli.h"
int TcpConnect(TCPClient *p, const char *str, int port) {
if (NULL == p || NULL == str) {
return -1;
}
struct sockaddr_in tmpsock;
memcpy((void *)p->strAddr, str, strlen(str));
p->iPort = port;
p->CientSocket = socket(AF_INET, SOCK_STREAM, 0);
tmpsock.sin_port = htons(port);
tmpsock.sin_addr.s_addr = inet_addr(str);
tmpsock.sin_family = AF_INET;
bzero(tmpsock.sin_zero, 8);
p->LocalAddr = tmpsock;
int iRet = connect(p->CientSocket, (const struct sockaddr *)&p->LocalAddr, sizeof(struct sockaddr));
if(iRet<0)
printf("error connect socker %d errno %d\n",iRet,errno);
return iRet;
}
int TcpSend(TCPClient *p, char pStr[], int iLen) {
if (NULL == p || NULL == pStr) {
return -1;
}
#ifdef WIN32
int iRet = send(p->CientSocket, pStr, iLen, 0);
if (iRet < 0) {
closesocket(p->CientSocket);
p->CientSocket = -1;
}
return iRet;
#endif
#ifdef linux
int iRet = send(p->CientSocket, pStr, iLen, MSG_DONTWAIT);
if (iRet < 0) {
close(p->CientSocket);
p->CientSocket = -1;
}
if(iRet != iLen){
printf("error socket send %d\n", iRet);
}
return iRet;
#endif
}
int TcpRecv(TCPClient *p, char pStr[], int iLen) {
int iRet = -1;
int iOffset = 0;
if (NULL == p || NULL == pStr) {
return -1;
}
#ifdef WIN32
iRet = recv(p->CientSocket, pStr, iLen, 0);
if (iRet < 0) {
closesocket(p->CientSocket);
p->CientSocket = -1;
}
#endif
#ifdef linux
iRet = recv(p->CientSocket, pStr + iOffset, iLen, 0);
printf("%s\n", pStr);
if (iRet < 0) {
close(p->CientSocket);
p->CientSocket = -1;
}
if(pStr[iRet + iOffset -4] !='\r' &&pStr[iRet +iOffset -3] != '\n'
&&pStr[iRet + iOffset -2] !='\r' &&pStr[iRet +iOffset -1] != '\n')
{
iOffset += iRet;
}
#endif
return iRet;
}
int TcpClose(TCPClient *p) {
#ifdef WIN32
p->CientSocket = -1;
closesocket(p->CientSocket);
return 0;
#endif
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化