socket编程
Web服务器1-socket编程
time服务器的客户端服务器,提交程序运行截图
实验代码(部分)
client
typedef struct{
int rio_fd;
int rio_cnt;
char *rio_bufptr;
char rio_buf[RIO_BUFSIZE];
}rio_t;
define MAXLINE 200
int main(int argc,char **argv){
int clientfd,port;
char *host,buf[MAXLINE];
char sbuf[MAXLINE];
char rbuf[MAXLINE];
rio_t rio;
char str1[MAXLINE]="客户端IP:";
char str2[MAXLINE]="服务器实现者学号:20201205";
char str3[MAXLINE]="当地时间:";
if(argc!=3){
fprintf(stderr,"usage:%s <host> <port>\n",argv[0]);
exit(0);
}
host = argv[1];
port = atoi(argv[2]);
clientfd = open_clientfd(host,port);
while(1){
recv(clientfd,rbuf,MAXLINE,0);
printf("%s",str1);
puts(host);
printf("%s",str2);
putchar('\n');
printf("%s",str3);
puts(rbuf);
close(clientfd);
exit(0);
}
}
server
typedef struct{
int rio_fd;
int rio_cnt;
char *rio_bufptr;
char rio_buf[RIO_BUFSIZE];
}rio_t;
typedef struct sockaddr SA;
typedef struct{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
}tm;
void sigchld_handler(int sig){
pid_t pid;
int stat;
while((pid = waitpid(-1,&stat,WNOHANG))>0){
printf("child %d terminated\n",pid);
}
return;
}
int main(int argc,char **argv){
int listenfd,connfd,port,clientlen;
struct sockaddr_in clientaddr;
struct hostent *hp;
char *haddrp;
char sbuf[MAXLINE];
char rbuf[MAXLINE];
rio_t rio;
time_t lt;
tm *local;
char str1[MAXLINE]="客户端IP:";
char str2[MAXLINE]="服务器实现者学号:";
char str3[MAXLINE]="当地时间:";
if(argc != 2){
fprintf(stderr,"usage:%s <port>\n",argv[0]);
exit(0);
}
port = atoi(argv[1]);
signal(SIGCHLD,sigchld_handler);
listenfd = open_listenfd(port);
while(1){
clientlen = sizeof(clientaddr);
connfd = accept(listenfd,(SA *)&clientaddr,&clientlen);
hp = gethostbyaddr((const char*)&clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr),AF_INET);
haddrp = inet_ntoa(clientaddr.sin_addr);
printf("server connected to %s (%s)\n",hp->h_name,haddrp);
if(fork() == 0){
close(listenfd);
lt = time(NULL);
local = localtime(<);
strftime(sbuf,64,"%Y-%m-%d %H:%M:%S",local);
send(connfd,sbuf,MAXLINE,0);
close(connfd);
exit(0);
}
close(connfd);
}
}
运行截图:


echo服务器的客户端服务器,提交程序运行截图,服务器把客户端传进来的内容加入“服务器进程pid 你的学号 姓名 echo :”返回给客户端
运行截图:


服务器部署到华为云服务器,客户端用Ubuntu虚拟机。
client端

要用多线程或者多进程实现,至少连接两个客户端
两个客户端


server端


浙公网安备 33010602011771号