概述
实验三-并发程序-1
- 学习使用Linux命令wc(1)
基于Linux Socket程序设计实现wc(1)服务器(端口号是你学号的后6位)和客户端
客户端传一个文本文件给服务器
服务器返加文本文件中的单词数
上方提交代码
附件提交测试截图,至少要测试附件中的两个文件
命令参数:
-c 统计字节数。
-l 统计行数。
-m 统计字符数。这个标志不能与 -c 标志一起使用。
-w 统计字数。一个字被定义为由空白、跳格或换行字符分隔的字符串。
-L 打印最长行的长度。
-help 显示帮助信息
--version 显示版本信息server
´´´include <sys/time.h>
include <stdlib.h>
include <stdio.h>
include <string.h>
include <unistd.h>
include <sys/types.h>
include <sys/socket.h>
include <netinet/in.h>
include <arpa/inet.h>
define PORT 155306
define BACKLOG 1
define MAXRECVLEN 1024
int main(int argc, char argv[])
{
char buf[MAXRECVLEN];
int listenfd, connectfd; / socket descriptors /
struct sockaddr_in server; / server's address information /
struct sockaddr_in client; / client's address information /
socklen_t addrlen;
/ Create TCP socket /
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
/ handle exception */
perror("socket() error. Failed to initiate a socket");
exit(1);
}
/* set socket option */
int opt = SO_REUSEADDR;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(listenfd, (struct sockaddr *)&server, sizeof(server)) == -1)
{
/* handle exception */
perror("Bind() error.");
exit(1);
}
if(listen(listenfd, BACKLOG) == -1)
{
perror("listen() error. n");
exit(1);
}
addrlen = sizeof(client);
while(1){
if((connectfd=accept(listenfd,(struct sockaddr *)&client, &addrlen))==-1)
{
perror("accept() error. n");
exit(1);
}
FILE *stream;
struct timeval tv;
gettimeofday(&tv, NULL);
printf(" Client ip : %s n",inet_ntoa(client.sin_addr));
printf(" Port id : %d n ",htons(client.sin_port));
printf("Time is %ld.%ldn",tv.tv_sec,tv.tv_usec);
int iret=-1;
char d[1024];
iret = recv(connectfd, buf, MAXRECVLEN, 0);
if(iret>0)
{
strcpy(d,buf);
stream = fopen(buf,"r");
bzero(buf, sizeof(buf));
//strcat(buf,"Word number:");
strcat(buf,"Word number:");
char s[21];
long int count = 0;
while(fscanf(stream,"%s",s)!=EOF)
count++;
char str[10];
sprintf(str, " %ldn", count);
int n = sizeof(str);
str[n] = '