学习完前面的api后,就可以编写一些简单的客户/服务器的小例子了,这里举一个例子(呵呵,很久没编程了,练练手拉) 编写一个回射服务器(也就是客户端发消息过来,服务器就消息写回客户端)
服务器:
# include //定义宏AF_INET,SOCK_STREAM,struct sockaddr
#include // 定义struct sockaddr_in,宏IPPROTO_TCP,INADDR_ANY
#include
#include //定义ssize
#include // 定义系统调用原型
#include // 服务器父进程处理sigchld信号,以防止子进程退出时因为父进程忽略
sigchld使子进程成为僵死进程
#define BUFFERSIZE 255;
#define PORT 1000
typedef void sigfuc (int)
sigfuc *signal(int signo, sigfunc *func)
{ struct sigaction nact,oact;
nact.sa_handler=func;
sigemptyset(&nact.sa_mask);
nact.sa_flags=SIG_RESTART;
if(sigacton(signo,nact,oact)<0)
return SIG_ERR;
else return (oact.sa_handler);
}
void handler (int signo)
{ pid_t pid;
int stat;
pid=wait(&stat);
printf("%d terminated\n",pid);
}
void main(int argc, void *argv[])
{ int fam =AF_INET;
int typ=SOCK_STREAM;
proto=IPPROTO_TCP;
int lisfd,confd;
sigfunc oldfunc;
if((lisfd=socket(fam,typ,proto)<0)
{
printf("%s\n","can not open the listen socket!");
exit(1);
}
struct sockaddr_in server,client;
memset(server,0,sizeof(struct sockaddr_in));
memset(client,0,sizeof(struct sockaddr_in));
server.family=AF_INET;
server.sin_port=htons(PORT)
server.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(lisfd,(const struct sockaddr *)&server,sizeof(struct sockaddr))<0)
{ printf("%s\n","can not bind local host 's socket address struct!");
exit(1);
}
if(listen(lisfd,10)<0)
{ printf("%s\n","can not make listen_socket listen!");
exit(1);
}
oldfunc=signal(SIGCHLD,handler)
int pid;
char buffer[BUFFERSIZE];
for(;;)
{ if((confd=accept(lisfd,(const sockaddr *)&client,sizeof(struct sockaddr)))<0)
{ printf("%s\n","can not get connection!");
exit(1);
}
pid=fork();
if(pid<0)
{printf("%s\n","can not fork child process to do action!");
exit(1);
}
else if(pid==0)
{ close (lisfd);
ssize_t readnum;
memset(buffer,0,BUFFERSIZE);
while((readnum=read(confd,buffer,BUFFERSIZE))>0)
write(confd,buffer,readnum);
close(confd);
exit(0);
}
else close(confd)
}
}
客户端:
#include
#include
.....
#define SERVERIP 192.*.*.*
#define PORT 1000
void main()
{
int confd;
if((confd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)<0)
{
printf("%s\n","can not open the connect socket!");
exit(1);
}
struct sockaddr_in server;
bzero(server,sizeof(struct sockaddr_in));
server.family=AF_INET;
server.sin_port=htons(PORT)
server.sin_addr.s_addr=htonl(SREVRIP);
if(connect(confd,(const struct sockaddr *)&server,sizeof(struct sockaddr))<0)
{ printf("%s\n","can not make a connection to the server!");
exit(1);
}
char buffer[BUFFERSIZE];
while(fgets(buffer,BUFFERSIZE,stdin)!=null)
{ write(confd,buffer,sizof(buffer));
bzero(buffer,BUFFERSIZE);
while((readnum =read(confd,buffer,BUFFERSIZE))>0)
fputs(buffer,stdout);
}
}
不管是window平台,还是unix平台,简单的socket编程的思路大致都是这样。