#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXSOCKFD 10
#define GSMD_UNIX_SOCKET "\0gsmd"
#define GSMD_UNIX_SOCKET_TYPE SOCK_STREAM
int main(int argc,char *argv[])
{
int sockfd,newsockfd,is_connected[MAXSOCKFD],fd;
struct sockaddr_un addr;
int addr_len = sizeof(struct sockaddr_in);
fd_set readfds;
char buffer[256];
char msg[ ] ="Welcome to server!";
if ((sockfd = socket(PF_UNIX, GSMD_UNIX_SOCKET_TYPE, 0))<0){//isockfd = socket(AF_INET,SOCK_STREAM,0)
perror("socket");
exit(1);
}
bzero(&addr,sizeof(addr));
/*
addr.sin_family =AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
*/
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, GSMD_UNIX_SOCKET, sizeof(GSMD_UNIX_SOCKET));
if(bind(sockfd,(struct sockaddr *)&addr,sizeof(addr))<0){// bind(sockfd,(struct sockaddr *)&addr,sizeof(addr)
perror("connect");
exit(1);
}
if(listen(sockfd,10)<0){
perror("listen");
exit(1);
}
for(fd=0;fd is_connected[fd]=0;
while(1)
{
FD_ZERO(&readfds);
FD_SET(sockfd,&readfds);
//加入到is_connected【】数组中,数组下标为文件描述符,对应的数组值为0或1表示是否为连接
for(fd=0;fd if(is_connected[fd])
FD_SET(fd,&readfds);
//
if(!select(MAXSOCKFD,&readfds,NULL,NULL,NULL))
continue;
for(fd=0;fd {
if(FD_ISSET(fd,&readfds))
{
if(sockfd == fd)
{
if((newsockfd = accept (sockfd,(struct sockaddr *)&addr,(socklen_t*)&addr_len))<0)
perror("accept");
write(newsockfd,msg,sizeof(msg));
is_connected[newsockfd] =1;
//printf("cnnect from %s\n",inet_ntoa(addr.sin_addr));
}else{
bzero(buffer,sizeof(buffer));
if(read(fd,buffer,sizeof(buffer))<=0)
{
printf("connect closed.\n");
is_connected[fd]=0;
close(fd);
}
else
printf("%s\n",buffer);
}
}
}
}
}
-----------
client.c
-----------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define GSMD_UNIX_SOCKET "\0gsmd"
#define GSMD_UNIX_SOCKET_TYPE SOCK_STREAM
int main(int argc,char *argv[])
{
int rc;
int fd;
struct sockaddr_un sun;
char data[12]="9999\n";
/* use unix domain socket to gsm daemon */
printf("starting...\n");
fd = socket(PF_UNIX, GSMD_UNIX_SOCKET_TYPE, 0);
if (fd < 0)
return fd;
printf("starting...\n");
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
memcpy(sun.sun_path, GSMD_UNIX_SOCKET, sizeof(GSMD_UNIX_SOCKET));
printf("starting...\n");
rc = connect(fd, (struct sockaddr *)&sun, sizeof(sun));
if (rc < 0) {
printf("not connect...\n");
close(fd);
fd = -1;
return rc;
}
for(;;){
usleep(100000);
send(fd, data, strlen(data), 0);
}
printf("end\n");
return 0;
}
阅读(1982) | 评论(0) | 转发(1) |