- 论坛徽章:
- 0
|
后来我又些了一个linux的服务端测试程序,客户端采用delphi,发送字符串,服务端将之打出来,情况和上面的一样,代码如下
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int srvsock;
int cltsock[3];
int main(int argc,char* argv[])
{
int i,k,j,len;
struct sockaddr_in local;
fd_set rdfs,wrfs,errfs;
struct timeval tv;
struct sockaddr addr;
char msgbuf[512];
for(i = 0; i < 3; i++)
cltsock[i] = 0;
srvsock = socket(AF_INET, SOCK_STREAM, 0);
if (srvsock < 0)
{
printf("\nsocket error" ;
return 1;
}
i = fcntl(srvsock, F_SETFL, O_NONBLOCK);
if (i < 0)
{
printf("\nfcntl error" ;
close(srvsock);
return 1;
}
k = 1;
i = setsockopt(srvsock, SOL_SOCKET, SO_REUSEADDR, &k, sizeof(int));
if (i < 0)
{
printf("\nsetsockopt error" ;
close(srvsock);
return 1;
}
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
local.sin_port = htons(5500);
i = bind(srvsock, (struct sockaddr *)&local, sizeof(local));
if (i < 0)
{
printf("\nbind error" ;
close(srvsock);
return 1;
}
i = listen(srvsock, 3);
if (i < 0)
{
printf("\nlisten error" ;
close(srvsock);
return 1;
}
for(;
{
FD_ZERO(&rdfs);
FD_ZERO(&errfs);
FD_SET(srvsock,&rdfs);
FD_SET(srvsock,&errfs);
for(i = 0; i < 3; i++)
if (cltsock[i] > 0)
{
FD_SET(cltsock[i],&rdfs);
FD_SET(cltsock[i],&errfs);
}
tv.tv_sec = 1;
tv.tv_usec=0;
k = srvsock;
for(i = 0; i < 3; i++)
if (cltsock[i] > k) k = cltsock[i];
i = select(k + 1,&rdfs,NULL,&errfs,&tv);
if ( i==0) continue;
if ( i > 0)
{
if (FD_ISSET(srvsock,&rdfs))
{
j = sizeof(addr);
k = accept(srvsock,&addr,&j);
if (k > 0)
{
if (cltsock[0] > 0) close(cltsock[0]);
cltsock[0] = k;
j = fcntl(k, F_SETFL, O_NONBLOCK);
if (j < 0)
{
printf("\ncltsock fcntl error" ;
close(k);
}
}
}
if (FD_ISSET(srvsock,&errfs))
{
printf("\nsrvsock err" ;
close(srvsock);
return 1;
}
if (FD_ISSET(cltsock[0],&rdfs))
{
memset(msgbuf,0x0,512);
len = recv(cltsock[0],msgbuf,512,MSG_NOSIGNAL);
if (len == 0)
{
close(cltsock[0]);
printf("\nthe peer close" ;
}
if (len < 0)
{
if ( errno != EAGAIN)
{
close(cltsock[0]);
printf("\nthe peer close due to error" ;
}
}
printf("\ndata income,len:%d,content:%s",len,msgbuf);
}
}
}
return 0;
} |
|