Apr 25, 2009

改写为C/S模式

上次贴的C代码有不少不规范的地方
随着学习的深入我把代码改写了下,写成C/S模式,但是运行时客户端只能连上一次服务器然后就断开。正在DEBUG

----------------------------makefile-------------------------------------------
# This makefile will generate "filetool" with fileoperator.c and fileoperator.h
# Author: Youbin Wang
# Date: 2009.04.17

OBJECTS=menu.o puberr.o simplecli.o
INCLUDE=-I/home/user01/NO05/include
MYPATH=/home/user01/NO05/bin
SERVEROBJ=simplesrv.o

all:filetool server

filetool: $(OBJECTS)
gcc -o filetool $(OBJECTS)
mv filetool $(MYPATH)

menu.o:menu.c
gcc $(INCLUDE) -c menu.c
`
puberr.o:puberr.c
gcc $(INCLUDE) -c puberr.c

simplecli.o:simplecli.c
gcc $(INCLUDE) -c simplecli.c

server : $(SERVEROBJ) puberr.o
gcc -o server $(SERVEROBJ) puberr.o
mv server $(MYPATH)

simplesrv.o:simplesrv.c
gcc $(INCLUDE) -c simplesrv.c

clean:
rm $(OBJECTS) $(SERVEROBJ)


------------------------------------menu.c-----------------------------------
/* -------------------------------------------------------
* $Source : menu.c 16-apr-2009.17:00:00 Youbin Wang $
* Function: Provide main menu and invoke client socket function
* Author : Youbin Wang
* Record :
2009.04.24 Change programme to c/s structure.
* 2009.04.22 Add errlog.
* 2009.04.16 Add the Version commentary.
* 2009.04.15 Create the main programme.
* ------------------------------------------------------- */
#include
#include
#include
#include
#include


/* -------------------------------------------------------
* global values
* ------------------------------------------------------- */
char * g_syslog="mytest";
char * g_print_str="testfile";

/* -------------------------------------------------------
* Show main menu if user haven't decided to exit the system
* or they just finish one operation
* Input parameter: none
* Output Parameter: return 0 while execute successfully
* ------------------------------------------------------- */
int show_menu()
{
printf(" --------------------------------------------\n");
printf(" Welcome TO This Programme \n");
printf(" This is the Main Menu \n");
printf(" --------------------------------------------\n");
printf("\n");
printf("Please Make your selection\n");
printf(" 1: Create a new file and write;\n");
printf(" 2: Open a file and write;\n");
printf(" 3: Open a file with read-only mode;\n");
printf(" 4: Exit;\n");
printf("\n");
return 0;
}


/* -------------------------------------------------------
* if the user choose to exit the system then invoke this function
* InputParameter:None
* OutputParameter: retrun 0 while execute successfully
* ------------------------------------------------------- */
int exit_system()
{
printf("\n");
printf("Exiting.........\n");
printf("\n");
printf(" Thank you for using this system.\n");
printf("\n");
printf(" If you have any problems or advices,contract the author at qisi1986@gmail.com\n");
printf("\n");
printf(" Wish you a good day. Bye Bye.\n");
return 0;
}

/* -------------------------------------------------------
* invoke if the user input the selection
* InputParamete r: the selection of user
* OutputParameter: return 0 while successfully
* Hint : if the user put the wrong key then it will provide hints
* ------------------------------------------------------- */
int selection(int Index)
{
int i_return=1;
printf("Your Selection is %d \n", Index);
printf("Now will invoke corresponding function,please wait.");
printf("\n");
sleep(1);
switch(Index)
{
case 1:
i_return = use_socket("127.0.0.1",1);
break;
case 2:
i_return = use_socket("127.0.0.1",2);
break;
case 3:
i_return = use_socket("127.0.0.1",3);
break;
case 4:
exit_system();
break;
default:
printf("Error!Please Enter a correct number!\n");
pub_err(2,__FILE__,__LINE__,g_syslog,"Enter an error number %s\n",g_print_str);
sleep(1);
}
if(0 == i_return)
printf("Operation successfully!!\n");
else
{
printf("Opeartion failed, please retry!\n");
i_return = 1;
return 1;
}
i_return = 1;
return 0;
}

int main()
{
int inputInt;
system("clear");
while(inputInt != 4)
{
system("clear");
show_menu();
printf("Enter your selection here: ");
scanf("%d", &inputInt);
selection(inputInt);
}
return 0;
}

-------------------------------puberr.c----------------------------------
#include
#include
#include
#include
#include
#include

#define FNAME_LEN 128
void pub_time(long *plHostDate, long *plHostTime)
{
struct tm *p;
time_t tmp;

time(&(tmp));
p = localtime(&tmp);
p->tm_year += 1899;

if (plHostDate != NULL)
*plHostDate =
(p->tm_year + 1) * 10000 + (p->tm_mon + 1) * 100 + p->tm_mday;
if (plHostTime != NULL)
*plHostTime = p->tm_hour * 10000 + p->tm_min * 100 + p->tm_sec;
return;
}


int _p_log(char *tmp_buf)
{
char logname[FNAME_LEN];
FILE *fp_log;
long l_date, l_time;

/*错误日志 */
pub_time(&l_date, &l_time);
sprintf(logname, "%s/log/pub_err%ld.log", getenv("HOME"),l_date);
// sprintf(logname, "../log/pub_err%ld.log", l_date);

if ((fp_log = fopen(logname, "a")) != NULL) {
fprintf(fp_log, "[%06ld/%06ld] %s\n", l_date % 1000000, l_time, tmp_buf);

fclose(fp_log);
}
else
{
fprintf(stderr, "[%06ld/%06ld] %s\n", l_date % 1000000, l_time, tmp_buf);
}

return 0;
}

/*
int pub_err(ret_code, file, line, recode, ...)
int ret_code;
char *file;
long line;
char *recode
*/
int pub_err(int ret_code, char *file, long line, char *recode, ...)
{
short i;
char *fmt, tmp_buf[2048], log[2048];
va_list args;

memset(tmp_buf, 0, 2048);
va_start(args,recode);
fmt = va_arg(args, char *);
vsprintf(tmp_buf, fmt, args);
va_end(args);
if (ret_code >= 0)
{
sprintf(log, "run message [%s][%ld][%s]", file, line,tmp_buf);
_p_log(log);
}
return ret_code;
}


------------------------------simplecli.c--------------------------------
/* ----------------------------------------------------------------
* simplecli.c
* Function:provide use_socket to set up a client socket
* and send the selection of user to server
* Record of Modification:
* 2009.04.24:Create function user_socket and test main
* ---------------------------------------------------------------- */

#include
#include
#include
#include
#include
#include


// define the defualt connect port id
#define SERVER_PORT 20130
// define the defualt client port as a random port
#define CLIENT_PORT ((20001+rand())%65536)
#define BUFFER_SIZE 255
#define REUQEST_MESSAGE "welcome to connect the server.\n"


int use_socket(char* ip, int i_select)
{
int servfd,clifd,length = 0;
int recvbyte;
struct sockaddr_in servaddr,cliaddr;
socklen_t socklen = sizeof(servaddr);
char buf[BUFFER_SIZE];

if ((clifd = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("create socket error!\n");
exit(1);
}
srand(time(NULL));//initialize random generator

bzero(&cliaddr,sizeof(cliaddr));
cliaddr.sin_family = AF_INET;
cliaddr.sin_port = htons(CLIENT_PORT);
cliaddr.sin_addr.s_addr = htons(INADDR_ANY);

bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
//inet_aton(argv[1],&servaddr.sin_addr);
//servaddr.sin_addr.s_addr=inet_addr(ip);
inet_aton(ip,&servaddr.sin_addr);
servaddr.sin_port = htons(SERVER_PORT);
//servaddr.sin_addr.s_addr = htons(INADDR_ANY);

if (bind(clifd,(struct sockaddr*)&cliaddr,sizeof(cliaddr))<0)
{
printf("bind to port %d failure!\n",CLIENT_PORT);
exit(1);
}
if (connect(clifd,(struct sockaddr*)&servaddr, socklen) < 0)
{
printf("can't connect to %s!\n",ip);
exit(1);
}

send(servfd,(char *)&i_select,sizeof(i_select),0);
length = recv(clifd,(char *)&recvbyte,sizeof(recvbyte),0);
if(length < 0)
{
printf("error comes when recieve data from server %s!", ip);
exit(1);
}
if(recvbyte == 0)
{
close(clifd);
return 0;
}
else
{
close(clifd);
exit(1);
}
}

/*-----------this is the test main function of use_socket-----------
int main()
{
int i=3;
if(use_socket("127.0.0.1", i))
printf("successful");
else
printf("failed");
return 0;

}-------------------------------------------------------------------*/

--------------------------simplesrv.c-------------------------------------
/* -------------------------------------------------------
* simplesrv.c
* Function:Start the server and listen a port
* When client send data, it recieve data
* deal with the data and send feedback info
* Record of Modification:
* 2009.04.23: Create it.
* -------------------------------------------------------*/
#include
#include
#include
#include
#include
#include
#include
#include "puberr.h"

#define SERVER_PORT 20130 // define the defualt connect port id
#define LENGTH_OF_LISTEN_QUEUE 10 //length of listen queue in server
#define BUFFER_SIZE 255
#define WELCOME_MESSAGE "welcome to connect the server. "


/* -------------------------------------------------------
* global values
* ------------------------------------------------------- */
char * g_syslog="mytest";
char * g_print_str="testfile";

/* -------------------------------------------------------
* invoke when the user choose to open a file with readonly mode(3)
* InputParameter:None
* OutputParameter: return 0 if execute successfully, 1 if error occured
* ------------------------------------------------------- */
int open_file_readonly()
{
char c_output;
FILE *fl_p_readonly;
fl_p_readonly = fopen("mytext.txt","rt");

printf("Reading mytext.txt ...\n");
if(NULL==fl_p_readonly)
{
pub_err(2, __FILE__, __LINE__, g_syslog, "Cannot open file mytext.txt in read-only mode %s\n", g_print_str);
getchar();
return 1;
}

printf("Open file successfully! \n");
sleep(1);
c_output=fgetc(fl_p_readonly);
while(c_output!=EOF)
{
printf("Reading the text...\n");
sleep(1);
putchar(c_output);
c_output=fgetc(fl_p_readonly);
}
fclose(fl_p_readonly);
pub_err(2, __FILE__, __LINE__, g_syslog,"Close the file %s\n", g_print_str);
return 0;
}

/* -------------------------------------------------------
* invoke when the user choose to create a new file(1)
* InputParameter: None
* OutputParameter: return 0 if execute successfully, 1 if error accured
* -------------------------------------------------------*/
int create_file()
{
printf("Creating a file ..\n");
FILE *fl_createfile;
fl_createfile = fopen("new.txt","wt+");
if(NULL==fl_createfile)
{
pub_err(2, __FILE__, __LINE__, g_syslog, "Cannot create a file %s\n",g_print_str);
getchar();
return 1;
}
char c_inputchar;
printf("Successfully create a file...\n");
sleep(1);
printf("Please input your text: \n");
while (c_inputchar!='\n')
{
printf("I'm reading your input\n");
fputc(c_inputchar,fl_createfile);
c_inputchar=getchar();
}
/* rewind the position of file pointer to the top of file */
rewind(fl_createfile);
printf("Your inputment is: ");
c_inputchar=fgetc(fl_createfile);
while(c_inputchar!=EOF)
{
printf("I'm writing your input\n");
putchar(c_inputchar);
c_inputchar=fgetc(fl_createfile);
}
printf("\n");
fclose(fl_createfile);
printf("Done!!\n");
sleep(1);
return 0;
}

/* -------------------------------------------------------
* if the user choose to open a exist file(2) and write then invoke this function
* InputParameter:None
* OutputParameter: return 0 if execute successfully, 1 if an error occured
* ------------------------------------------------------- */
int open_file()
{
printf("Opening a file...\n");
FILE *fl_openfile;
fl_openfile = fopen("mytext.txt","wt+");
if(NULL==fl_openfile)
{
pub_err(2,__FILE__,__LINE__,g_syslog,"Cannot open a file %s\n",g_print_str);
getchar();
return 1;
}

char c_inputchar;
printf("Successfully open a file");
printf("Please input your text: \n");
while (c_inputchar!='\n')
{
fputc(c_inputchar,fl_openfile);
c_inputchar=getchar();
}
/* rewind the position of file pointer to the top of file */
rewind(fl_openfile);
printf("Your inputment is: ");
c_inputchar=fgetc(fl_openfile);
while(c_inputchar!=EOF)
{
putchar(c_inputchar);
c_inputchar=fgetc(fl_openfile);
}
printf("\n");
fclose(fl_openfile);
printf("Done!!\n");
sleep(1);
return 0;
}

/* -------------------------------------------------------
* invoke if the user input the selection
* InputParamete r: the selection of user
* OutputParameter: return 0 while successfully
* Hint : if the user put the wrong key then it will provide hints
* ------------------------------------------------------- */
int selection(int i_input)
{
switch(i_input)
{
case 1:
create_file();
break;
case 2:
open_file();
break;
case 3:
open_file_readonly();
break;
default:
pub_err(2,__FILE__,__LINE__,g_syslog,"Enter an error number %s\n",g_print_str);
return 1;
}
return 0;
}


int main(int argc, char **argv)
{
int servfd,clifd,recvbyte;
int length=0;
int sel_feedback=1;
struct sockaddr_in servaddr,cliaddr;
if ((servfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("create socket error!\n");
exit(1);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERVER_PORT);
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
if (bind(servfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)
{
printf("bind to port %d failure!\n",SERVER_PORT);
exit(1);
}
if (listen(servfd,LENGTH_OF_LISTEN_QUEUE) < 0)
{
printf("call listen failure!\n");
exit(1);
}

while (1)
{//server loop will nerver exit unless any body kill the process
char buf[BUFFER_SIZE];
long timestamp;
socklen_t length = sizeof(cliaddr);
clifd = accept(servfd,(struct sockaddr*)&cliaddr,&length);
if (clifd < 0)
{
printf("error comes when call accept!\n");
break;
}
strcpy(buf,WELCOME_MESSAGE);
//inet_ntop(INET_ADDRSTRLEN,cliaddr.sin_addr,buf,BUFFER_SIZE);
printf("from client,IP:%s,Port:%d\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
timestamp = time(NULL);
strcat(buf,"timestamp in server:");
strcat(buf,ctime(×tamp));
//send(clifd,buf,BUFFER_SIZE,0);
length=recv(servfd,(char *)&recvbyte,sizeof(recvbyte),0);
if(length<0)
{
printf("error comes when recieve data from client");
close(clifd);
exit(1);
}
sel_feedback = selection(recvbyte);
send(clifd,(char *)sel_feedback,sizeof(sel_feedback),0);
close(clifd);
sel_feedback = 1;
}//exit
close(servfd);
return 0;
}

No comments:

Powered By Blogger