Friday, November 22, 2013

Unix Network Programming: FTP using message queue

Algorithm

Create a structute that defines a message item in the message queue, say messageBuf

Client Side
  1. Get a message queue
  2. Read a filename from the standard input
  3. Set the message type as 1 and send the message
  4. Read messages of type 2 from the mesaage queue
  5. display the contents read
Server Side
  1. Get a message queue
  2. Read the filename from the meassage queue with type as 1
  3. Open requested file
  4. Read contents from the file and write into the message queue with type as 2
  5. Close the file

Program

message.h
 
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define PERMS 0666
#define KEY1 2345
#define TYPE1 100
#define TYPE2 111
#define SIZE 20

struct messageBuf{
    int type;
    char msg[SIZE];
}

server
#include<stdio.h>
#include<malloc.h>
#include<fcntl.h>
#include<string.h>
#include "message.h"
main()
{
    int mq1,fd,n;
    struct messageBuf *m1 = (struct messageBuf *)malloc(sizeof(struct messageBuf));
    if(mq1 = msgget(KEY1,PERMS|IPC_CREAT)<0)
        printf("Error: Message Q unavaillable\n");
    msgrcv(mq1,m1,sizeof(struct messageBuf),TYPE1,0);
    printf("File Requested:%s\n",m1->msg);
    fd = open(m1->msg, O_RDONLY, 0);
    if(fd<0)
        printf("Error: Unable to open requested file\n");
    do
    {
        n = read(fd,m1->msg,SIZE);
        m1->type = TYPE2;
        msgsnd(mq1, m1, n, 0);
    }while(n==SIZE);
    close(fd);
}

client
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include "message.h"

main()
{
    int mq1,n;
    struct messageBuf *m1 = (struct messageBuf *)malloc(sizeof(struct messageBuf));
    if(mq1 = msgget(KEY1,PERMS|IPC_CREAT)<0)
        printf("Error: Message Q unavaillable\n");
    printf("Enter Required file name: ");
    scanf("%s",m1->msg);
    m1->type = TYPE1;
    msgsnd(mq1, m1, strlen(m1->msg),0);
    do{
        n = msgrcv(mq1,m1,SIZE,TYPE2,0);
        printf("%s",m1->msg);
    }while(n==SIZE);
}

Run the server and client from two different windows

Output

Client window

Enter Required file name: message.h
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define PERMS 0666
#define KEY1 2345
#define TYPE1 100
#define TYPE2 111
#define SIZE 20

struct messageBuf{
    int type;
    char msg[SIZE];
}

Server window
File Requested:message.h

No comments:

Post a Comment