公共代码:
#pragma once #include<stdio.h> #include<stdint.h> #include<string.h> #include<unistd.h> #include<arpa/inet.h> #include<stdlib.h> #include<time.h> #include<stdbool.h> #include<signal.h> #include<sys/wait.h> #define SERVERPORT 9999 #define FTM_STAMP "%lld\r\n" #define PROCNUM 4 #define lv_exit(str)\ perror(str);\ exit(1);
服务端代码:
#include "proto.h" static void serverjob(int confd) { char buf[512] = {0}; int len = sprintf(buf, FTM_STAMP, (long long)time(NULL)); if (send(confd, buf, len, 0) < 0) { perror("send"); exit(1); } } static void server_loop(int sfd) { struct sockaddr_in cliaddr; socklen_t clilen = sizeof cliaddr; while (1) { int confd = accept(sfd, (void *)&cliaddr, &clilen); if (confd < 0) { perror("accept"); exit(1); } printf("[%d]client %s %d\n",getpid(),inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port)); serverjob(confd); close(confd); } close(sfd); } int main(int argc, char const *argv[]) { int sfd = socket(AF_INET, SOCK_STREAM, 0); if (sfd < 0) { perror("socket"); exit(1); } struct sockaddr_in seraddr; seraddr.sin_family = AF_INET; seraddr.sin_port = htons(9999); seraddr.sin_addr.s_addr = inet_addr("192.168.244.154"); int val = 1; if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof val) < 0) { perror("setsockopt"); exit(1); } if (bind(sfd, (void *)&seraddr, sizeof seraddr) < 0) { perror("bind"); exit(1); } if (listen(sfd, 10) < 0) { perror("listen"); exit(1); } signal(SIGCHLD, SIG_IGN); printf("pid=%d\n",getpid()); for (size_t i = 0; i < PROCNUM; i++) { pid_t pid = fork(); if (pid < 0) { perror("fork"); exit(1); } if (pid == 0) { server_loop(sfd); exit(0); } } for (size_t i = 0; i < PROCNUM; i++) { wait(NULL); } puts("fu"); close(sfd); return 0; }
客户端代码:
#include"proto.h" int main(int argc, char const *argv[]) { int sfd=socket(AF_INET,SOCK_STREAM,0); if(sfd<0){ perror("socket"); exit(1); } struct sockaddr_in seraddr; seraddr.sin_family=AF_INET; seraddr.sin_port=htons(SERVERPORT); seraddr.sin_addr.s_addr=inet_addr("192.168.244.154"); if(connect(sfd,(void*)&seraddr,sizeof seraddr)<0){ perror("connect"); exit(1); } FILE* fp= fdopen(sfd,"r+"); if (fp==NULL) { perror("fdopen"); exit(1); } long long stamp; if(fscanf(fp,FTM_STAMP,&stamp)<1){ fprintf(stderr,"Bad format!\n"); }else { fprintf(stdout,"stamp=%lld\n",stamp); } fclose(fp); return 0; }
测试流程:
1、启动服务端:
2、启动客户端 watch -n 1 ./cli
3、打开网络检测工具
watch -n 1 "netstat -tan | grep 9999"
4、执行ps -a 监视进程数
0.0分
1 人评分
校门外的树 (C++代码)浏览:908 |
Tom数 (C语言代码)浏览:784 |
C语言训练-求素数问题 (C语言代码)浏览:989 |
C语言程序设计教程(第三版)课后习题8.1 (C语言代码)浏览:776 |
K-进制数 (C++代码)浏览:940 |
C语言训练-求具有abcd=(ab+cd)2性质的四位数 (C语言代码)浏览:626 |
矩阵乘法 (C++代码)浏览:1665 |
数组输出 (C语言代码)--此题的题目描述有问题浏览:1846 |
C语言程序设计教程(第三版)课后习题6.10 (C语言代码)浏览:588 |
【魔板】 (C++代码)(时间超限,希望会的帮我改正一下)浏览:805 |