码迷,mamicode.com
首页 > 其他好文 > 详细

2017-2018-1 20155333 《信息安全系统设计基础》实验三

时间:2017-11-20 01:19:18      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:accept   声明   ext   queue   fclose   信息安全   ges   receive   vptr   

2017-2018-1 20155333 《信息安全系统设计基础》实验三

实验三-并发程序-1

  • 学习使用Linux命令wc(1)
  • 基于Linux Socket程序设计实现wc(1)服务器(端口号是你学号的后6位)和客户端
  • 客户端传一个文本文件给服务器
  • 服务器返加文本文件中的单词数
  • 提交代码
  • 提交测试截图,至少要测试附件中的两个文件

技术分享图片

mywc.c
#include<stdio.h>
#include<string.h>

#define LEN 4096

int text_c(FILE *fp)
{
    char buffer[LEN];
    int i=0,count=0;

    while(fgets(buffer,LEN,fp)!=NULL)
    {
        while(buffer[i]!=‘\0‘)
        {
            if(buffer[i]!=‘\n‘ && buffer[i]!=‘ ‘)
                ++count;
            i++;
        }
        i=0;
    }
    return count;
}

int text_l(FILE *fp)
{
    char buffer[LEN];
    int  count=0;
    while(fgets(buffer,LEN,fp)!=NULL)
                ++count;
    return count;
}

int text_w(FILE *fp)
{
    char buffer[LEN];
    int i=0,count=0;
    while(fgets(buffer,LEN,fp)!=NULL)
    {
        while(buffer[i]!=‘\0‘)
        {
            if(buffer[i]==‘ ‘ || buffer[i]==‘,‘ || buffer[i]==‘.‘ || buffer[i]==‘!‘ ||buffer[i]==‘?‘)
                 ++count;
            i++;
        }
        i=0;
    }
    return count;
}

int main()
{
    FILE *fp;
    char choice;
    int data;
    fp=fopen("test2.txt","r+");
    if(fp==NULL)
        printf("no file found!please check your path!");
    choice=getchar();
    switch(choice)
    {
        case ‘l‘:
           data=text_l(fp);
           fclose(fp);
           printf("line:%d\n",data);
           break;
        case ‘c‘:
           data=text_c(fp);
           fclose(fp);
           printf("character:%d\n",data);
           break;
        case ‘w‘:
           data=text_w(fp);
           fclose(fp);
           printf("word:%d\n",data);
           break;
        default:
            break;
    }
}
server.c
#include<netinet/in.h> // sockaddr_in 
#include<sys/types.h>  // socket 
#include<sys/socket.h> // socket 
#include<stdio.h>    // printf 
#include<stdlib.h>   // exit 
#include<string.h>   // bzero 

#define SERVER_PORT 8000 
#define LEN 4096
#define LENGTH_OF_LISTEN_QUEUE 20 
#define BUFFER_SIZE 1024 
#define FILE_NAME_MAX_SIZE 512 
  
int main(void) 
{ 
  // 声明并初始化一个服务器端的socket地址结构 
  struct sockaddr_in server_addr; 
  bzero(&server_addr, sizeof(server_addr)); 
  server_addr.sin_family = AF_INET; 
  server_addr.sin_addr.s_addr = htons(INADDR_ANY); 
  server_addr.sin_port = htons(SERVER_PORT); 
  
  // 创建socket,若成功,返回socket描述符 
  int server_socket_fd = socket(PF_INET, SOCK_STREAM, 0); 
  if(server_socket_fd < 0) 
  { 
    perror("Create Socket Failed:"); 
    exit(1); 
  } 
  int opt = 1; 
  setsockopt(server_socket_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); 
  
  // 绑定socket和socket地址结构 
  if(-1 == (bind(server_socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)))) 
  { 
    perror("Server Bind Failed:"); 
    exit(1); 
  } 
    
  // socket监听 
  if(-1 == (listen(server_socket_fd, LENGTH_OF_LISTEN_QUEUE))) 
  { 
    perror("Server Listen Failed:"); 
    exit(1); 
  } 
  
  while(1) 
  { 
    // 定义客户端的socket地址结构 
    struct sockaddr_in client_addr; 
    socklen_t client_addr_length = sizeof(client_addr); 
  
    // 接受连接请求,返回一个新的socket(描述符),这个新socket用于同连接的客户端通信 
    // accept函数会把连接到的客户端信息写到client_addr中 
    int new_server_socket_fd = accept(server_socket_fd, (struct sockaddr*)&client_addr, &client_addr_length); 
    if(new_server_socket_fd < 0) 
    { 
      perror("Server Accept Failed:"); 
      break; 
    } 
  
    // recv函数接收数据到缓冲区buffer中 
    char buffer[BUFFER_SIZE]; 
    bzero(buffer, BUFFER_SIZE); 
    if(recv(new_server_socket_fd, buffer, BUFFER_SIZE, 0) < 0) 
    { 
      perror("Server Recieve Data Failed:"); 
      break; 
    } 
  
    // 然后从buffer(缓冲区)拷贝到file_name中 
    char file_name[FILE_NAME_MAX_SIZE+1]; 
    bzero(file_name, FILE_NAME_MAX_SIZE+1); 
    strncpy(file_name, buffer, strlen(buffer)>FILE_NAME_MAX_SIZE?FILE_NAME_MAX_SIZE:strlen(buffer)); 
    printf("%s\n", file_name); 
  
    // 打开文件并读取文件数据 
    FILE *fp = fopen(file_name, "r+"); 
    if(NULL == fp) 
    { 
      printf("File:%s Not Found\n", file_name); 
    } 
    else
    { 
      bzero(buffer, BUFFER_SIZE); 
      int length = 0; 
      // 每读取一段数据,便将其发送给客户端,循环直到文件读完为止 
      while((length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0) 
      { 
        if(send(new_server_socket_fd, buffer, length, 0) < 0) 
        { 
          printf("Send File:%s Failed./n", file_name); 
          break; 
        } 
        bzero(buffer, BUFFER_SIZE); 
      } 
  
      // 关闭文件 
      fclose(fp); 
      printf("File:%s Transfer Successful!\n", file_name); 
    } 
    // 关闭与客户端的连接 
    close(new_server_socket_fd); 
  } 
  // 关闭监听用的socket 
  close(server_socket_fd); 
  return 0; 
} 
client.c
#include<netinet/in.h>  // sockaddr_in 
#include<sys/types.h>  // socket 
#include<sys/socket.h>  // socket 
#include<stdio.h>    // printf 
#include<stdlib.h>    // exit 
#include<string.h>    // bzero 


#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>



#define LEN 4096
#define SERVER_PORT 8000 
#define BUFFER_SIZE 1024 
#define FILE_NAME_MAX_SIZE 512 



int main() 
{ 
  // 声明并初始化一个客户端的socket地址结构 
  struct sockaddr_in client_addr; 
  bzero(&client_addr, sizeof(client_addr)); 
  client_addr.sin_family = AF_INET; 
  client_addr.sin_addr.s_addr = htons(INADDR_ANY); 
  client_addr.sin_port = htons(0); 
  
  // 创建socket,若成功,返回socket描述符 
  int client_socket_fd = socket(AF_INET, SOCK_STREAM, 0); 
  if(client_socket_fd < 0) 
  { 
    perror("Create Socket Failed:"); 
    exit(1); 
  } 
  
  // 绑定客户端的socket和客户端的socket地址结构 非必需 
  if(-1 == (bind(client_socket_fd, (struct sockaddr*)&client_addr, sizeof(client_addr)))) 
  { 
    perror("Client Bind Failed:"); 
    exit(1); 
  } 
  
  // 声明一个服务器端的socket地址结构,并用服务器那边的IP地址及端口对其进行初始化,用于后面的连接 
  struct sockaddr_in server_addr; 
  bzero(&server_addr, sizeof(server_addr)); 
  server_addr.sin_family = AF_INET; 
  if(inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) == 0) 
  { 
    perror("Server IP Address Error:"); 
    exit(1); 
  } 
  server_addr.sin_port = htons(SERVER_PORT); 
  socklen_t server_addr_length = sizeof(server_addr); 
  
  // 向服务器发起连接,连接成功后client_socket_fd代表了客户端和服务器的一个socket连接 
  if(connect(client_socket_fd, (struct sockaddr*)&server_addr, server_addr_length) < 0) 
  { 
    perror("Can Not Connect To Server IP:"); 
    exit(0); 
  } 
  
  // 输入文件名 并放到缓冲区buffer中等待发送 
  char file_name[FILE_NAME_MAX_SIZE+1]; 
  bzero(file_name, FILE_NAME_MAX_SIZE+1); 
  printf("Please Input File Name On Server:\t"); 
  scanf("%s", file_name); 
  
  char buffer[BUFFER_SIZE]; 
  bzero(buffer, BUFFER_SIZE); 
  strncpy(buffer, file_name, strlen(file_name)>BUFFER_SIZE?BUFFER_SIZE:strlen(file_name)); 
    
  // 向服务器发送buffer中的数据 
  if(send(client_socket_fd, buffer, BUFFER_SIZE, 0) < 0) 
  { 
    perror("Send File Name Failed:"); 
    exit(1); 
  } 
  
  // 打开文件,准备写入 
  FILE *fp = fopen(file_name, "w"); 
  if(NULL == fp) 
  { 
    printf("File:\t%s Can Not Open To Write\n", file_name); 
    exit(1); 
  } 
  
  // 从服务器接收数据到buffer中 
  // 每接收一段数据,便将其写入文件中,循环直到文件接收完并写完为止 
  bzero(buffer, BUFFER_SIZE); 
  int length = 0; 
  while((length = recv(client_socket_fd, buffer, BUFFER_SIZE, 0)) > 0) 
  { 
    if(fwrite(buffer, sizeof(char), length, fp) < length) 
    { 
      printf("File:\t%s Write Failed\n", file_name); 
      break; 
    } 
    bzero(buffer, BUFFER_SIZE); 
  }
  

  
  // 接收成功后,关闭文件,关闭socket 
  printf("Receive File:\t%s From Server IP Successful!\n", file_name); 
  close(fp); 
  close(client_socket_fd); 
  
int pid = fork();
char *argv[]={"wc","-w",file_name,0};  
execvp( "wc" ,argv);
wait (&pid); 
return 0;
}

截图如下:
技术分享图片
技术分享图片

实验三-并发程序-2

  • 使用多线程实现wc服务器并使用同步互斥机制保证计数正确
  • 提交代码
  • 提交测试
  • 对比单线程版本的性能,并分析原因
server.c
#include <stdio.h>
#include <stdlib.h>
#include<pthread.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <dirent.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#define LEN 4096  
#define MAXLINE 40
#define BUFFERSIZE 4096
#define PORT 13321
#define BUFFER_LENGTH 1024
#define MAX_CONN_LIMIT 512     //MAX connection limit
ssize_t writen(int fd, const void * vptr, size_t n)
{
    size_t nleft;
    ssize_t nwritten;
    const char * ptr;

    ptr = vptr;
    nleft = n;
    while ( nleft > 0)
     {
        if ((nwritten = write(fd, ptr, nleft)) <= 0)
        {
            if (nwritten < 0 && errno == EINTR) 
            {
                nwritten = 0;
            }
            else
            {
                return -1;
            }
        }

        nleft -= nwritten;
        ptr += nwritten; 
    }
    return n;
}

ssize_t readline(int fd, void * vptr, size_t maxlen)
{
    ssize_t    n, rc;
    char    c, *ptr;
    ptr = vptr;
    for (n = 1; n < maxlen; n++)
    {
        again:
        if ((rc = read(fd, &c, 1)) == 1)
        {
            *ptr++ = c;
            if (c == ‘\n‘)
            {
                break;
            }
        }
        else if (rc == 0)
        {   
            *ptr = 0;
            return (n - 1);
        }
        else
        {
            if (errno == EINTR)
            {
                goto again;
            }
            return (-1);
        }
    }
    *ptr = 0;
    return (n);
}

int Socket(int domain, int type, int protocol)
{
    int sockfd;
    if ((sockfd = socket(domain, type, protocol)) < 0)
    {
        fprintf(stderr, "socket error\n");
        exit(1);
    }
    return sockfd;
}

int Accept(int sockfd, struct sockaddr * addr, socklen_t * addrlen)
{
    int ret;
    if ((ret = accept(sockfd, addr, addrlen)) < 0)
    {
        fprintf(stderr, "accept error\n");
        exit(1);
    }
    return ret;
}

int Bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
{
    int ret;
    if ((ret = bind(sockfd, addr, addrlen)) < 0)
    {
        fprintf(stderr, "bind error\n");
        exit(1);
    }
    return ret;
}

int Listen(int sockfd, int backlog)
{
    int ret;
    if ((ret = listen(sockfd, backlog)) < 0)
    {
        fprintf(stderr, "listen error\n");
        exit(1);
    }
    return ret;
}

int Close(int fd)
{
    int ret;
    if ((ret = close(fd)) < 0)
    {
        fprintf(stderr, "close error\n");
        exit(1);
    }
    return ret;
}


static void Data_handle(void * sock_fd)
{
     int fd = *((int *)sock_fd);
     int i_recvBytes;
     char data_recv[BUFFER_LENGTH];
     const char * data_send = "Server has received your request!\n";
     pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
     while(1)
     {
        pthread_mutex_lock( &counter_mutex );
        int totalNum[1] = {0};
        FILE *fp;  // 指向文件的指针
        char buffer[1003];  //缓冲区,存储读取到的每行的内容
        int bufferLen;  // 缓冲区中实际存储的内容的长度
        int i;  // 当前读到缓冲区的第i个字符
        char c;  // 读取到的字符
        int isLastBlank = 0;  // 上个字符是否是空格
        int charNum = 0;  // 当前行的字符数
        int wordNum = 0; // 当前行的单词数
        if( (fp=fopen("/home/rafel/shiyan3/2/save", "rb")) == NULL ){
            perror(filename);
            exit(1);
        }
    
    while(fgets(buffer, 1003, fp) != NULL){
        bufferLen = strlen(buffer);
        // 遍历缓冲区的内容
        for(i=0; i<bufferLen; i++){
            c = buffer[i];
            if( c==‘ ‘ || c==‘\t‘){  // 遇到空格
                !isLastBlank && wordNum++;  // 如果上个字符不是空格,那么单词数加1
                isLastBlank = 1;
            }else if(c!=‘\n‘&&c!=‘\r‘){  // 忽略换行符
                charNum++;  // 如果既不是换行符也不是空格,字符数加1
                isLastBlank = 0;
            }
        }
        !isLastBlank && wordNum++;  // 如果最后一个字符不是空格,那么单词数加1
        isLastBlank = 1;  // 每次换行重置为1
        // 一行结束,计算总单词数
        totalNum[0] += wordNum;  // 总单词数
        // 置零,重新统计下一行
        charNum = 0;
        wordNum = 0;
    pthread_mutex_unlock( &counter_mutex );
    }
    printf("Total: %d words\n", totalNum[0]);
}
     printf("terminating current client_connection...\n");
     close(fd);            //close a file descriptor.
     pthread_exit(NULL);   //terminate calling thread!
 }

int main(void)
{
    int listenfd, connfd;
    char    buff[BUFFERSIZE + 1];
    char    filename[BUFFERSIZE + 1];
    char    cd[BUFFERSIZE+1];
    char    choose[10];
    struct sockaddr_in  servaddr, cliaddr;
    int cliaddrlen;
    int filefd;   
    int count;
    DIR *dir;
    struct dirent   *ptr;
    listenfd = Socket(AF_INET, SOCK_STREAM, 0);
    
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = INADDR_ANY;
    servaddr.sin_port = htons(PORT);
    Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    Listen(listenfd, 5);

    while(1)
    {
        printf("开始监听\n");

        cliaddrlen = sizeof(cliaddr);
        connfd = Accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddrlen);

        if (readline(connfd, buff, BUFFERSIZE) < 0)
        {
            fprintf(stderr, "readline error\n");
            exit(1);
        }
        buff[strlen(buff) - 1] = 0;    /* change ‘\n‘ to NUL */
        memcpy(filename, buff, BUFFERSIZE + 1);
        printf("统计的文件名: %s\n", buff);
        
        printf("Input the direct you want to store %s:\n", buff);
        scanf("%s", cd);
        if(chdir(cd) < 0)
        {
            fprintf(stderr, "direct error\n");
            exit(1);
        }

        dir = opendir(cd);
        while((ptr = readdir(dir)) != NULL)
        {
            if(strcmp(buff, ptr->d_name) == 0)
            {
                printf("已存在文件:%s\n", buff);
                printf("若想重命名请输入yes,否则请输入no\n");    
                scanf("%s", choose);
                if(strcmp(choose, "yes") == 0)
                {           
                    printf("重命名为:\t");
                    scanf("%s", buff);
                }
            }
        }

        filefd = open(buff, O_WRONLY | O_CREAT);
        if (filefd < 0)
        {
            fprintf(stderr, "can‘t open the file: %s\n", buff);
            exit(1);
        }

        while(count = read(connfd, buff, BUFFERSIZE))
        {
            if (count < 0)
            {
                fprintf(stderr, "connfd read error\n");
                exit(1);
            }
            if (writen(filefd, buff, count) < 0) 
            {
                fprintf(stderr, "writing to filefd error\n");
                exit(1);
            }
        }
        
    int sockfd = Accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddrlen);
    //sockfd = accept(sockfd_server,(struct sockaddr*)(&s_addr_client),(socklen_t *)(&client_length));

    pthread_t thread_id;
    if(pthread_create(&thread_id,NULL,(void *)(&Data_handle),(void *)(&sockfd)) == -1)
         {
             fprintf(stderr,"pthread_create error!\n");
             break;                                  //break while loop
         }


        if(pthread_create(&thread_id,NULL,(void *)(&Data_handle),(void *)(&sockfd)) == -1)
         {
             fprintf(stderr,"pthread_create error!\n");
             break;                                  //break while loop
         }
        closedir(dir);
        Close(filefd);
        Close(connfd);
        printf("file %s received!\n", filename);
}
}
client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#define MAXLINE 40
#define BUFFERSIZE 4096
#define PORT 13321
ssize_t writen(int fd, const void * vptr, size_t n)
{
    size_t    nleft;
    ssize_t    nwritten;
    const char *    ptr;

    ptr = vptr;
    nleft = n;
    while (nleft > 0) 
    {
        if ((nwritten = write(fd, ptr, nleft)) <= 0) 
        {
            if (nwritten < 0 && errno == EINTR) 
            {
                nwritten = 0;
            }
            else 
            {
                return -1;
            }
        }

        nleft -= nwritten;
        ptr += nwritten;
    }

    return n;
}

int Socket(int domain, int type, int protocol)
{
    int sockfd;
    if ((sockfd = socket(domain, type, protocol)) < 0) 
    {
        fprintf(stderr, "socket error\n");
        exit(1);
    }

    return sockfd;
}

int Connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
{
    int ret;
    if ((ret = connect(sockfd, addr, addrlen)) < 0) 
    {
        fprintf(stderr, "connect error\n");
        exit(1);
    }

    return ret;
}


int Close(int fd)
{
    int ret;
    if ((ret = close(fd)) < 0) 
    {
        fprintf(stderr, "close error\n");
        exit(1);
    }

    return ret;
}


int main(int argc, char *argv[])
{
    if (argc != 3) 
    {
        fprintf(stderr, "Usage: ./fileclient <file> <serverIP>\n");
        exit(1);
    }

    int sockfd;
    char buff[BUFFERSIZE + 1];
    char filenameheader[BUFFERSIZE + 1];
    struct sockaddr_in servaddr;
    int filefd;    /* file descriptor */
    int count;

    sockfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr=INADDR_ANY;
    servaddr.sin_port = htons(PORT);
    
    
    Connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    printf("已连接服务器\n");

    printf("需统计的文件名为: %s........\n", argv[1]);
    memcpy(filenameheader, argv[1], strlen(argv[1]));
    filenameheader[strlen(argv[1])] = ‘\n‘;
    filenameheader[strlen(argv[1]) + 1] = 0;
    writen(sockfd, filenameheader, strlen(filenameheader));

    printf("正上传文件%s至服务器\n", argv[1]);

    filefd = open(argv[1], O_RDONLY);
    if (filefd < 0) 
    {
        fprintf(stderr, "can‘t open the file: %s\n", argv[1]);
        exit(1);
    }

    while(count = read(filefd, buff, BUFFERSIZE)) 
    {
        if (count < 0) 
        {
            fprintf(stderr, "filefd read error\n");
            exit(1);
        }
        if (writen(sockfd, buff, count) < 0) 
        {
            fprintf(stderr, "writing to sockfd error\n");
            exit(1);
        }
    }   
    Close(filefd);
    Close(sockfd);
    printf("文件%s已上传至服务器!\n", argv[1]);
    return 0;
}

截图如下:
技术分享图片

多线程实现的关键在于互斥的计数,即为当某一个线程计数时,另一个线程就不能计数

实验三-并发程序-3

  • 交叉编译多线程版本服务器并部署到实验箱中
  • PC机作客户端测试wc服务器
  • 提交测试截图
    第三个任务暂未完成,下次实验时补上。

2017-2018-1 20155333 《信息安全系统设计基础》实验三

标签:accept   声明   ext   queue   fclose   信息安全   ges   receive   vptr   

原文地址:http://www.cnblogs.com/rh123456/p/7863024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!