linux gcc下实现简单socket套接字小程序
服务端代码如下:
//服务端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <netdb.h>
//捕获子进程退出信号,在退出时给出提示
void sig_handler(int signo)
{
pid_t pid;
int stat;
pid=waitpid(-1,&stat,WNOHANG);
while(pid>0){
printf("子进程结束 (PID:%ld)\n",(long)getpid());
pid=waitpid(-1,&stat,WNOHANG);
}
}
int main(int argc,char *argv[])
{
socklen_t clt_addr_len;
int listen_fd;
int com_fd;
int ret;
int i;
static char recv_buf[1024];
int len;
int port;
pid_t pid;
struct sockaddr_in clt_addr;
struct sockaddr_in srv_addr;
//提示
if (argc!=2){
printf("exp: %s port\n",argv[0]);
return 1;
}
port=atoi(argv[1]);
//设置信号处理函数
if(signal(SIGCHLD,sig_handler)<0){
perror("cannot set the signal");
return 1;
}
//设置套接字监听
listen_fd=socket(PF_INET,SOCK_STREAM,0);
if(listen_fd<0){
perror("不能创建套接字监听!");
return 1;
}
memset(&srv_addr,0,sizeof(srv_addr));
srv_addr.sin_family=AF_INET;
srv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
srv_addr.sin_port=htons(port);
ret=bind(listen_fd,(struct sockaddr*)&srv_addr,sizeof(srv_addr));
if(ret == -1){
perror("不能捆绑端口");
close(listen_fd);
return 1;
}
//监听指定端口,连接5个客户端
ret=listen(listen_fd,5);
if(ret==-1){
perror("不能监听端口");
close(listen_fd);
return 1;
}
while (1){
len=sizeof(clt_addr);
com_fd=accept(listen_fd,(struct sockaddr*)&clt_addr,&len);
if(com_fd<0){
if(errno == EINTR){
continue;
}else{
perror("不能返回结果");
close(listen_fd);
return 1;
}
}
pid=fork();//多进程
if(pid<0){
perror("不能创建子进程!");
close(listen_fd);
return 1;
}else if(pid == 0){
while((len=read(com_fd,recv_buf,1024))>0){
printf("连接端信息:(%d):%s\n",len,recv_buf);
if(recv_buf[0]=='@')
break;
for(i=0;i<len;i++)
recv_buf[i]=toupper(recv_buf[i]);
write(com_fd,recv_buf,len);
}
close(com_fd);
return 0;
}else
close(com_fd);
}
return 0;
}
客户端代码如下:
//客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int connect_fd;
int ret;
char snd_buf[1024];
int i;
int port;
int len;
static struct sockaddr_in srv_addr;
if(argc!=3){
printf("exp: %s server_ip port\n",argv[0]);
return 1;
}
port=atoi(argv[2]);
connect_fd=socket(PF_INET,SOCK_STREAM,0);
if(connect_fd<0){
perror("Cannot create communication socket");
return 1;
}
memset(&srv_addr,0,sizeof(srv_addr));
srv_addr.sin_family=AF_INET;
srv_addr.sin_addr.s_addr=inet_addr(argv[1]);
srv_addr.sin_port=htons(port);
//连接到服务器
ret=connect(connect_fd,(struct sockaddr*)&srv_addr,sizeof(srv_addr));
if(ret==-1){
perror("Cannot connect to the server");
close(connect_fd);
return 1;
}
memset(snd_buf,0,1024);
while(1){
write(STDOUT_FILENO,"In put some Message",14);
len=read(STDIN_FILENO,snd_buf,1024);
if(len>0)
write(connect_fd,snd_buf,len);
len=read(connect_fd,snd_buf,len);
if(len>0)
printf("The message from Server %s\n",snd_buf);
if(snd_buf[0] == '@')
break;
}
close(connect_fd);
return 0;
}
运行如下图:
代码来自《LINUX编程技术详解》。PS:Vim快把电脑的空格键用坏了,囧。