User Tools

Site Tools


cs444kim:ctvcge18

FORTUNE SERVER

/*
 * fortuneserver.c - a simple server which when asked for send a quick fortune
 *
 * Cassidy Gibson
 * STARTED: 4/24/18
 * UPDATED: 4/30/18
 */

#include <stdio.h>
#include "csapp.h"
#include <stdlib.h>

void fortune(int connfd);
void get_fortune();

char lines[400][MAXLINE]; 

int main(int argc, char **argv) {
  int listenfd, connfd;
  char hostname[MAXLINE], port[MAXLINE];
  socklen_t clientlen;
  struct sockaddr_storage clientaddr;

  if(argc != 2){
    fprintf(stderr, "usage: %s <port> \n", argv[0]);
    exit(1);
  }

  get_fortune();

  listenfd = Open_listenfd(argv[1]);
  while(1) {
    clientlen = sizeof(clientaddr);
    connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
    Getnameinfo((SA *) &clientaddr, clientlen, hostname, MAXLINE, port, MAXLINE, 0);
    printf("Accepted connection from (%s, %s \n", hostname, port);
    fortune(connfd);
    Close(connfd);
  }
}

void fortune(int fd){
  char *bufs = lines[rand() %347];
  char wowza[MAXLINE];
  int n;
  rio_t rio;

  Rio_readinitb(&rio,fd);
  if ((n = Rio_readlineb(&rio, wowza, MAXLINE)) != 0){
    printf("wowza");
    printf("%s\n", wowza);
    Rio_writen(fd, bufs, strlen(bufs));
  }
 // mirror this closer to the echo server... i think
}

void get_fortune(){
  static const char filename[] = "fortune.txt";
  FILE *file = fopen(filename, "r");

  if (file != NULL){
    int i = 0;
    while((fgets(lines[i], MAXLINE, file)) != NULL){
      i++;
    }
  } else {
    perror(filename);
  } 
}

FORTUNECLIENT

/**
* fortuneclien.c is a simple client that when asked, reqests a fortune from the
* server and displays response
*
* CREATED: 4/26/18
* UPDATED: 4/30/18
**/

#include "csapp.h"

int main(int argc, char **argv){
  int clientfd;
  char *host, *port, buf[MAXLINE];
  rio_t rio;

  host = argv[1];
  port = argv[2];

  clientfd = Open_clientfd(host, port);
  Rio_readinitb(&rio, clientfd);

  Rio_writen(clientfd, "give me\n", strlen("give me\n"));
  Rio_readlineb(&rio, buf, MAXLINE);
  Fputs(buf, stdout);

  Close(clientfd);
  exit(0); 
}
cs444kim/ctvcge18.txt · Last modified: 2018/04/30 16:27 by scarl