user-0 提问: 多线程并发服务器字符串加密反转，遇quit退出

回复:
user: user-1
content: 引用 5 楼 zyl730 的回复:[quote=引用 4 楼 zhao4zhong1 的回复:] 多进程的话，参考 Microsoft SDK\samples\winbase\SharedMem\Consumer.Cpp Microsoft SDK\samples\winbase\SharedMem\Makefile Microsoft SDK\samples\winbase\SharedMem\Producer.Cpp Microsoft SDK\samples\winbase\SharedMem\Queue.h Microsoft SDK\samples\winbase\SharedMem\ReadMe.Txt Microsoft SDK\samples\winbase\SharedMem\Common.h不好意思，第一次混论坛，这个是要在哪里查看，不会。。。。[/quote] 搜索下载Microsoft SDK 6

user: user-0
content: 我刚才看了一下.......对不起，我标题写错了，是多进程，很抱歉

user: user-1
content: 仅供参考：//循环向a函数每次发送200个字节长度（这个是固定的）的buffer, //a函数中需要将循环传进来的buffer，组成240字节（也是固定的）的新buffer进行处理， //在处理的时候每次从新buffer中取两个字节打印 #ifdef _MSC_VER     #pragma warning(disable:4996) #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _MSC_VER     #include <windows.h>     #include <process.h>     #include <io.h>     #define  MYVOID             void     #define  vsnprintf          _vsnprintf #else     #include <unistd.h>     #include <sys/time.h>     #include <pthread.h>     #define  CRITICAL_SECTION   pthread_mutex_t     #define  MYVOID             void * #endif //Log{ #define MAXLOGSIZE 20000000 #define MAXLINSIZE 16000 #include <time.h> #include <sys/timeb.h> #include <stdarg.h> char logfilename1[]="MyLog1.log"; char logfilename2[]="MyLog2.log"; static char logstr[MAXLINSIZE+1]; char datestr[16]; char timestr[16]; char mss[4]; CRITICAL_SECTION cs_log; FILE *flog; #ifdef _MSC_VER void Lock(CRITICAL_SECTION *l) {     EnterCriticalSection(l); } void Unlock(CRITICAL_SECTION *l) {     LeaveCriticalSection(l); } void sleep_ms(int ms) {     Sleep(ms); } #else void Lock(CRITICAL_SECTION *l) {     pthread_mutex_lock(l); } void Unlock(CRITICAL_SECTION *l) {     pthread_mutex_unlock(l); } void sleep_ms(int ms) {     usleep(ms*1000); } #endif void LogV(const char *pszFmt,va_list argp) {     struct tm *now;     struct timeb tb;      if (NULL==pszFmt||0==pszFmt[0]) return;     vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);     ftime(&tb);     now=localtime(&tb.time);     sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);     sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );     sprintf(mss,"%03d",tb.millitm);     printf("%s %s.%s %s",datestr,timestr,mss,logstr);     flog=fopen(logfilename1,"a");     if (NULL!=flog) {         fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);         if (ftell(flog)>MAXLOGSIZE) {             fclose(flog);             if (rename(logfilename1,logfilename2)) {                 remove(logfilename2);                 rename(logfilename1,logfilename2);             }         } else {             fclose(flog);         }     } } void Log(const char *pszFmt,...) {     va_list argp;      Lock(&cs_log);     va_start(argp,pszFmt);     LogV(pszFmt,argp);     va_end(argp);     Unlock(&cs_log); } //Log} #define ASIZE    200 #define BSIZE    240 #define CSIZE      2 char Abuf[ASIZE]; char Cbuf[CSIZE]; CRITICAL_SECTION cs_HEX; CRITICAL_SECTION cs_BBB; struct FIFO_BUFFER {     int  head;     int  tail;     int  size;     char data[BSIZE]; } BBB; int No_Loop=0; void HexDump(int cn,char *buf,int len) {     int i,j,k;     char binstr[80];      Lock(&cs_HEX);     for (i=0;i<len;i++) {         if (0==(i%16)) {             sprintf(binstr,"%03d %04x -",cn,i);             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);         } else if (15==(i%16)) {             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);             sprintf(binstr,"%s  ",binstr);             for (j=i-15;j<=i;j++) {                 sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');             }             Log("%s\n",binstr);         } else {             sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);         }     }     if (0!=(i%16)) {         k=16-(i%16);         for (j=0;j<k;j++) {             sprintf(binstr,"%s   ",binstr);         }         sprintf(binstr,"%s  ",binstr);         k=16-k;         for (j=i-k;j<i;j++) {             sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');         }         Log("%s\n",binstr);     }     Unlock(&cs_HEX); } int GetFromRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {     int lent,len1,len2;      lent=0;     Lock(cs);     if (fbuf->size>=len) {         lent=len;         if (fbuf->head+lent>BSIZE) {             len1=BSIZE-fbuf->head;             memcpy(buf     ,fbuf->data+fbuf->head,len1);             len2=lent-len1;             memcpy(buf+len1,fbuf->data           ,len2);             fbuf->head=len2;         } else {             memcpy(buf     ,fbuf->data+fbuf->head,lent);             fbuf->head+=lent;         }         fbuf->size-=lent;     }     Unlock(cs);     return lent; } MYVOID thdB(void *pcn) {     char        *recv_buf;     int          recv_nbytes;     int          cn;     int          wc;     int          pb;      cn=(int)pcn;     Log("%03d thdB              thread begin...\n",cn);     while (1) {         sleep_ms(10);         recv_buf=(char *)Cbuf;         recv_nbytes=CSIZE;         wc=0;         while (1) {             pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);             if (pb) {                 Log("%03d recv %d bytes\n",cn,pb);                 HexDump(cn,recv_buf,pb);                 sleep_ms(1);             } else {                 sleep_ms(1000);             }             if (No_Loop) break;//             wc++;             if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);         }         if (No_Loop) break;//     } #ifndef _MSC_VER     pthread_exit(NULL); #endif } int PutToRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {     int lent,len1,len2;      Lock(cs);     lent=len;     if (fbuf->size+lent>BSIZE) {         lent=BSIZE-fbuf->size;     }     if (fbuf->tail+lent>BSIZE) {         len1=BSIZE-fbuf->tail;         memcpy(fbuf->data+fbuf->tail,buf     ,len1);         len2=lent-len1;         memcpy(fbuf->data           ,buf+len1,len2);         fbuf->tail=len2;     } else {         memcpy(fbuf->data+fbuf->tail,buf     ,lent);         fbuf->tail+=lent;     }     fbuf->size+=lent;     Unlock(cs);     return lent; } MYVOID thdA(void *pcn) {     char        *send_buf;     int          send_nbytes;     int          cn;     int          wc;     int           a;     int          pa;      cn=(int)pcn;     Log("%03d thdA              thread begin...\n",cn);     a=0;     while (1) {         sleep_ms(100);         memset(Abuf,a,ASIZE);         a=(a+1)%256;         if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop         send_buf=(char *)Abuf;         send_nbytes=ASIZE;         Log("%03d sending %d bytes\n",cn,send_nbytes);         HexDump(cn,send_buf,send_nbytes);         wc=0;         while (1) {             pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);             Log("%03d sent %d bytes\n",cn,pa);             HexDump(cn,send_buf,pa);             send_buf+=pa;             send_nbytes-=pa;             if (send_nbytes<=0) break;//             sleep_ms(1000);             if (No_Loop) break;//             wc++;             if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);         }         if (No_Loop) break;//     } #ifndef _MSC_VER     pthread_exit(NULL); #endif } int main() { #ifdef _MSC_VER     InitializeCriticalSection(&cs_log);     InitializeCriticalSection(&cs_HEX);     InitializeCriticalSection(&cs_BBB); #else     pthread_t threads[2];     int threadsN;     int rc;     pthread_mutex_init(&cs_log,NULL);     pthread_mutex_init(&cs_HEX,NULL);     pthread_mutex_init(&cs_BBB,NULL); #endif     Log("Start===========================================================\n");      BBB.head=0;     BBB.tail=0;     BBB.size=0;  #ifdef _MSC_VER     _beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);     _beginthread((void(__cdecl *)(void *))thdB,0,(void *)2); #else     threadsN=0;     rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);     rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1); #endif      if (!access("No_Loop",0)) {         remove("No_Loop");         if (!access("No_Loop",0)) {             No_Loop=1;         }     }     while (1) {         sleep_ms(1000);         if (No_Loop) break;//         if (!access("No_Loop",0)) {             No_Loop=1;         }     }     sleep_ms(3000);     Log("End=============================================================\n"); #ifdef _MSC_VER     DeleteCriticalSection(&cs_BBB);     DeleteCriticalSection(&cs_HEX);     DeleteCriticalSection(&cs_log); #else     pthread_mutex_destroy(&cs_BBB);     pthread_mutex_destroy(&cs_HEX);     pthread_mutex_destroy(&cs_log); #endif     return 0; }

user: user-2
content: 你的程序逻辑里没有对遇到quit退出的操作；如果需要建议在我修改的基础加上。

user: user-2
content: 服务器，注意对端发来的数据num是实际数据的长度，所以对于字符串结束标记加的位置应该为recvbuf[num] = 0; #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h>  #define PORT 1234 #define BACKLOG 5 #define MAXDATASIZE 1024 #define MAXNAMESIZE 64  void process_cli(int  connfd, struct sockaddr_in client);  int main() {     int  listenfd, connfd;     pid_t  pid;     struct  sockaddr_in  server;     struct sockaddr_in  client;     int  len;      if ((listenfd =socket(AF_INET, SOCK_STREAM, 0)) == -1)     {         perror("Creatingsocket failed.");         exit(1);     }      int opt =SO_REUSEADDR;     setsockopt(listenfd,SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));     bzero(&server,sizeof(server));     server.sin_family=AF_INET;     server.sin_port=htons(PORT);     server.sin_addr.s_addr= htonl (INADDR_ANY);     if (bind(listenfd,(struct sockaddr *)&server, sizeof(server)) == -1)     {         perror("Bind()error.");         exit(1);     }      if(listen(listenfd,BACKLOG)== -1)     {         perror("listen() error\n");         exit(1);     }     len=sizeof(client);     while(1)     {         if ((connfd =accept(listenfd,(struct sockaddr *)&client, (socklen_t *)&len))==-1) {             perror("accept() error\n");             exit(1);         }         if ((pid = fork())>0){             close(connfd);             //continue;         }         else if (pid==0) {             close(listenfd);             process_cli(connfd, client);             exit(0);         }         else         {             printf("fork()error\n");             exit(0);         }     }     close(listenfd); }  void process_cli(int connfd, struct sockaddr_in client) {     int num;     char  recvbuf[MAXDATASIZE], sendbuf[MAXDATASIZE], cli_name[MAXNAMESIZE];     printf("Yougot a connection from %s. ",inet_ntoa(client.sin_addr) );     num = recv(connfd,cli_name, MAXDATASIZE,0);     if (num == 0)     {         close(connfd);         printf("Client disconnected.\n");         return;     }     printf("num = %d\n", num);     cli_name[num] = '\0';     printf("Client's name is %s.\n", cli_name);      while ((num = recv(connfd, recvbuf, MAXDATASIZE, 0)) > 0)     {         recvbuf[num] = '\0';         printf("Receivedclient( %s ) message: %s\n", cli_name, recvbuf);         int i = 0;          for (i = 0; i < num; ++i)             sendbuf[i] = recvbuf[num - i - 1];          sendbuf[num] = '\0';    /* 若send中不用strlen(sendbuf)则这句是多余的*/         send(connfd, sendbuf, num, 0);         usleep(5000);   /*保证客户端分两次获取*/         for (i = 0;i < num; i++)         {             if((recvbuf[i]>='a' && recvbuf[i]<='z')||(recvbuf[i]>='A'&&recvbuf[i]<='Z'))             {                 recvbuf[i] += 4;   /*简单表达式*/                 if((recvbuf[i] > 'Z' && recvbuf[i] <= 'Z' + 4)||(recvbuf[i] > 'z'))                     recvbuf[i] = recvbuf[i]- 26;             }             sendbuf[i] = recvbuf[i];         }         sendbuf[num] = '\0';   /*这句不能少，因为下面send用到了strlen*/         send(connfd, sendbuf, strlen(sendbuf),0);      }     close(connfd); }    客户端；注意fgets会将回车符加入到缓存里； #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h>  #define PORT 1234 #define MAXDATASIZE 1024  void process(FILE*fp, int sockfd); char *getMessage(char* sendline,int len, FILE* fp);  int main(int argc,char *argv[]) {     int fd;     struct hostent  *he;     struct sockaddr_in  server;      if (argc !=2) {         printf("Usage:%s <IP Address>\n",argv[0]);         exit(1);     }      if((he=gethostbyname(argv[1]))==NULL)     {         printf("gethostbyname() error\n");         exit(1);     }     if((fd=socket(AF_INET, SOCK_STREAM, 0))==-1)     {         printf("socket()error\n");         exit(1);     }      bzero(&server,sizeof(server));     server.sin_family =AF_INET;     server.sin_port=htons(PORT);     server.sin_addr= *((struct in_addr *)he->h_addr);      if(connect(fd,(struct sockaddr *)&server,sizeof(server))==-1)     {         printf("connect() error\n");         exit(1);     }      process(stdin,fd);      close(fd);      return 0; }  void process(FILE *fp, int  sockfd) {     char sendline[MAXDATASIZE],recvline[MAXDATASIZE];     int num;      printf("Connected to server. \n");     printf("Input client's name : ");     if (fgets(sendline, MAXDATASIZE, fp) == NULL)     {         printf("\nExit.\n");         return;     }     sendline[strlen(sendline)-1] = 0;    /* delete '\n' */     send(sockfd,sendline, strlen(sendline), 0);     while(getMessage(sendline, MAXDATASIZE, fp) != NULL)     {         sendline[strlen(sendline)-1] = 0;    /* delete '\n' */         send(sockfd, sendline, strlen(sendline), 0);         //send(sockfd, sendline, num-1,0);         int i = 2;         while (i--) {    /* 第二次接收的是加密后的*/             if ((num = recv(sockfd, recvline, MAXDATASIZE,0)) == 0) {                 printf("Server terminated.\n");                 return;             }             recvline[num] = '\0';             if (i == 0)                 printf("Recv encrpt string from server: \n");             printf("server string return  :%s\n", recvline);             printf("Server Message: %s\n",recvline);         }     }     printf("\nExit.\n"); }  char  *getMessage(char*  sendline,int len, FILE*  fp) {     printf("Inputstring to server:");     return(fgets(sendline,MAXDATASIZE, fp)); }  参考一下吧。代码里也有其他问题，我不一一罗列。建议楼主拷贝到本地测试跑跑，和自己的代码对比一下（我在楼主的基础上修改的），消化一下多进程的socket编程；

user: user-0
content: 引用 4 楼 zhao4zhong1 的回复:多进程的话，参考 Microsoft SDK\samples\winbase\SharedMem\Consumer.Cpp Microsoft SDK\samples\winbase\SharedMem\Makefile Microsoft SDK\samples\winbase\SharedMem\Producer.Cpp Microsoft SDK\samples\winbase\SharedMem\Queue.h Microsoft SDK\samples\winbase\SharedMem\ReadMe.Txt Microsoft SDK\samples\winbase\SharedMem\Common.h不好意思，第一次混论坛，这个是要在哪里查看，不会。。。。

user: user-1
content: 多进程的话，参考 Microsoft SDK\samples\winbase\SharedMem\Consumer.Cpp Microsoft SDK\samples\winbase\SharedMem\Makefile Microsoft SDK\samples\winbase\SharedMem\Producer.Cpp Microsoft SDK\samples\winbase\SharedMem\Queue.h Microsoft SDK\samples\winbase\SharedMem\ReadMe.Txt Microsoft SDK\samples\winbase\SharedMem\Common.h

user: user-0
content: 引用 1 楼 zhao4zhong1 的回复://循环向a函数每次发送200个字节长度（这个是固定的）的buffer, //a函数中需要将循环传进来的buffer，组成240字节（也是固定的）的新buffer进行处理， //在处理的时候每次从新buffer中取两个字节打印我刚才看了一下.......对不起，我标题写错了，是多进程，很抱歉