当前位置: 技术问答>linux和unix
socket程序类似长连接问题!
来源: 互联网 发布时间:2016-06-29
本文导语: 从客户端两次调用send函数,但是却只能收到第一条,请问为什么,代码如下。 客户端: main() { char pSndPort[]="7666"; char pSndIp[]="127.0.0.1"; struct sockaddr_in srvaddr; iSktID=socket(AF_INET,SOCK_STREAM,0); ...
从客户端两次调用send函数,但是却只能收到第一条,请问为什么,代码如下。
客户端:
服务端:
客户端:
main()
{
char pSndPort[]="7666";
char pSndIp[]="127.0.0.1";
struct sockaddr_in srvaddr;
iSktID=socket(AF_INET,SOCK_STREAM,0);
bzero(&srvaddr,sizeof(srvaddr));
srvaddr.sin_family=AF_INET;
srvaddr.sin_port=htons(atoi(pSndPort));
srvaddr.sin_addr.s_addr= inet_addr(pSndIp);
connect(iSktID,(struct sockaddr *)&srvaddr,sizeof(struct sockaddr));
XmlSnd2Cis();
close(iSktID);
}
XmlSnd2Cis()
{
send(iSktID, "i love you", sizeof("i love you"), 0);
send(iSktID, "zsl", sizeof("zsl"), 0);
}
服务端:
main()
{
int nListenSock = 0, nSock = 0;
int nPort = 7666;
pid_t iPid;
signal(SIGCHLD,SIG_IGN);
CreateSock(&nListenSock, nPort, 8);
AcceptSock(&nSock, nListenSock);
while(1)
{ XmlRecv4Cis(nSock); }
}
int CreateSock(int* pSock, int nPort, int nMax)
{
struct sockaddr_in addrin;
memset(&addrin, 0, sizeof(addrin));
addrin.sin_family = AF_INET;
addrin.sin_addr.s_addr = htonl(INADDR_ANY);
addrin.sin_port = htons(nPort);
*pSock = socket(AF_INET, SOCK_STREAM, 0);
bind(*pSock, (struct sockaddr *)&addrin, sizeof(addrin));
listen(*pSock, nMax);
}
int AcceptSock(int* pSock, int nSock)
{
struct sockaddr_in addrin;
int lSize;
while (1)
{
lSize = sizeof(addrin);
memset(&addrin, 0, sizeof(addrin));
if ((*pSock = accept(nSock, (struct sockaddr *)&addrin, &lSize)) > 0)
return 0;
}
}
XmlRecv4Cis(int nSock)
{
char buf[100];
bzero(buf, sizeof(buf));
if(recv(nSock, buf, sizeof(buf), 0)