/* 服务器端server程序 */
/* 编译命令:gcc -Wall -g -o server server.c -lpthread */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#define PORT 8458
#define MAX_LISTEN 20
typedef struct MsgHead{
unsigned char type;
unsigned char BL[4];
}MH;
pthread_mutex_t mutex;
pthread_attr_t attr;
char *get_time_string(char *sbuf)
{
time_t Now;
struct tm *tm;
struct tm temp_time;
time (&Now);
tm = localtime_r(&Now, &temp_time);
sprintf(sbuf, "%.4d%.2d%.2d_%.2d%.2d%.2d",
tm->tm_year 1900, tm->tm_mon 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
return sbuf;
}
char *GetFileName(char *filename)
{
char strTime[20];
char strFileName[64];
memset(strTime,0x00,sizeof(strTime));
memset(strFileName,0x00,sizeof(strFileName));
sleep(1);
get_time_string(strTime);
strcpy(strFileName,"rec_");
strcat(strFileName,strTime);
strcat(strFileName,".dat");
strcpy(filename,strFileName);
return filename;
}
int tcp_recv(int fd,int len, char *strRecv)
{
char *p = strRecv;
int iRet = -1,iRecvLen = -1,count = 0;
fd_set rset;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
while(len > 0)
{
FD_ZERO(&rset);
FD_SET(fd,&rset);
iRet = select (fd 1,&rset,NULL,NULL,&tv);
//printf("iRet = %dn",iRet);
if (iRet < 0)
{
printf("tcp select error:%sn",strerror(errno));
break;
}
else if (iRet == 0)
{
sleep(1);
continue;
}
iRecvLen = recv(fd,p,len,0);
if (iRecvLen > 0)
{
len -= iRecvLen;
p = iRecvLen;
count = iRecvLen;
}
}
return count;
}
void *recv_msg(void *clfd)
{
MH *MsgHead = NULL;
int iMHL,iBodyLen,iRet = -1,iType = -1,iRecCount = 0;
char RecvBuf[1024] = {""},sFileName[64] = {""};
int fd = *((int *)clfd);
FILE *fp = NULL;
printf("clfd=%dn",fd);
iMHL = sizeof(MH);
/* 打开一个文件用于存放sql 语句 */
pthread_mutex_lock(&mutex);
GetFileName(sFileName);
pthread_mutex_unlock(&mutex);
printf("Filename:%sn",sFileName);
if ( 0 > strlen(sFileName))
{
printf("get filename failedn");
return NULL;
}
fp = fopen(sFileName,"w ");
if (!fp)
{
printf("open file %s failed: %sn",sFileName,strerror(errno));
return NULL;
}
fprintf(fp,"%sn","set termout on");
fprintf(fp,"%sn","set feed off");
while(1)
{
memset(RecvBuf,0X00,sizeof(RecvBuf));
//Get message head
iRet = tcp_recv(fd,iMHL,RecvBuf);
if (iRet != iMHL)
{
printf(&quo |