服务端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h>
#define PORT 8087
#define SERVER_IP “127.0.0.1”
#define BUFFER_SIZE 1024
#define FILE_NAME_MAX_SIZE 512
#pragma comment(lib, “WS2_32”)
int main()
{
// 声明并初始化一个服务端(本地)的地址结构
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.S_un.S_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 初始化socket dll
WSADATA wsaData;
WORD socketVersion = MAKEWORD(2, 0);
if (WSAStartup(socketVersion, &wsaData) != 0)
{
printf(“Init socket dll error!”);
exit(1);
}
// 创建socket
SOCKET m_Socket = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET_ERROR == m_Socket)
{
printf(“Create Socket Error!”);
exit(1);
}
//绑定socket和服务端(本地)地址
if (SOCKET_ERROR == bind(m_Socket, (LPSOCKADDR)&server_addr, sizeof(server_addr)))
{
printf(“Server Bind Failed: %d”, WSAGetLastError());
exit(1);
}
//监听
if (SOCKET_ERROR == listen(m_Socket, 10))
{
printf(“Server Listen Failed: %d”, WSAGetLastError());
exit(1);
}
while (1)
{
printf(“Listening To Client…\n”);
sockaddr_in client_addr;
int client_addr_len = sizeof(client_addr);
SOCKET m_New_Socket = accept(m_Socket, (sockaddr *)&client_addr, &client_addr_len);
if (SOCKET_ERROR == m_New_Socket)
{
printf(“Server Accept Failed: %d”, WSAGetLastError());
break;
}
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
if (recv(m_New_Socket, buffer, BUFFER_SIZE, 0) < 0)
{
printf(“Server Receive Data Failed!”);
break;
}
char file_name[FILE_NAME_MAX_SIZE + 1];
memset(file_name, 0, FILE_NAME_MAX_SIZE + 1);
strncpy_s(file_name, buffer, strlen(buffer)>FILE_NAME_MAX_SIZE ? FILE_NAME_MAX_SIZE : strlen(buffer));
printf(“%s\n”, file_name);
//打开文件,准备写入
FILE * fp;
errno_t err = fopen_s(&fp, file_name, “wb”); //windows下是”wb”,表示打开一个只写的二进制文件
if (err != 0)
{
printf(“File: %s Can Not Open To Write\n”, file_name);
system(“pause”);
exit(1);
}
else
{
memset(buffer, 0, BUFFER_SIZE);
unsigned int length = 0;
while ((length = recv(m_New_Socket, buffer, BUFFER_SIZE, 0)) > 0)
{
if (fwrite(buffer, sizeof(char), length, fp) < length)
{
printf(“File: %s Write Failed\n”, file_name);
break;
}
memset(buffer, 0, BUFFER_SIZE);
}
printf(“Receive File: %s From Server Successful!\n”, file_name);
}
fclose(fp);
closesocket(m_New_Socket);
}
//释放winsock库
WSACleanup();
system(“pause”);
return 0;
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h>
#define PORT 8087
#define SERVER_IP “127.0.0.1”
#define BUFFER_SIZE 1024
#define FILE_NAME_MAX_SIZE 512
#pragma comment(lib, “WS2_32”)
int main()
{
// 初始化socket dll
WSADATA wsaData;
WORD socketVersion = MAKEWORD(2, 0);
if (WSAStartup(socketVersion, &wsaData) != 0)
{
printf(“Init socket dll error!”);
exit(1);
}
//创建socket
SOCKET c_Socket = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET_ERROR == c_Socket)
{
printf(“Create Socket Error!”);
system(“pause”);
exit(1);
}
//指定服务端的地址
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.S_un.S_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
if (SOCKET_ERROR == connect(c_Socket, (LPSOCKADDR)&server_addr, sizeof(server_addr)))
{
printf(“Can Not Connect To Server IP!\n”);
system(“pause”);
exit(1);
}
//输入文件名
char file_name[FILE_NAME_MAX_SIZE + 1];
memset(file_name, 0, FILE_NAME_MAX_SIZE + 1);
printf(“Please Input File Name On Server: “);
scanf_s(“%s”, &file_name);
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
strncpy_s(buffer, file_name, strlen(file_name)>BUFFER_SIZE ? BUFFER_SIZE : strlen(file_name));
//向服务器发送文件名
if (send(c_Socket, buffer, BUFFER_SIZE, 0) < 0)
{
printf(“Send File Name Failed\n”);
system(“pause”);
exit(1);
}
FILE * fp;
errno_t err= fopen_s(&fp,file_name, “rb”); //windows下是”rb”,表示打开一个只读的二进制文件
if (err!=0)
{
printf(“File: %s Not Found\n”, file_name);
}
else
{
memset(buffer, 0, BUFFER_SIZE);
int length = 0;
while ((length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0)
{
if (send(c_Socket, buffer, length, 0) < 0)
{
printf(“Send File: %s Failed\n”, file_name);
break;
}Sleep(100);
memset(buffer, 0, BUFFER_SIZE);
}
fclose(fp);
printf(“File: %s Transfer Successful!\n”, file_name);
}
closesocket(c_Socket);
closesocket(c_Socket);
//释放winsock库
WSACleanup();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h>
#define PORT 8087
#define SERVER_IP “127.0.0.1”
#define BUFFER_SIZE 1024
#define FILE_NAME_MAX_SIZE 512
#pragma comment(lib, “WS2_32”)
int main()
{
// 声明并初始化一个服务端(本地)的地址结构
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.S_un.S_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 初始化socket dll
WSADATA wsaData;
WORD socketVersion = MAKEWORD(2, 0);
if (WSAStartup(socketVersion, &wsaData) != 0)
{
printf(“Init socket dll error!”);
exit(1);
}
// 创建socket
SOCKET m_Socket = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET_ERROR == m_Socket)
{
printf(“Create Socket Error!”);
exit(1);
}
//绑定socket和服务端(本地)地址
if (SOCKET_ERROR == bind(m_Socket, (LPSOCKADDR)&server_addr, sizeof(server_addr)))
{
printf(“Server Bind Failed: %d”, WSAGetLastError());
exit(1);
}
//监听
if (SOCKET_ERROR == listen(m_Socket, 10))
{
printf(“Server Listen Failed: %d”, WSAGetLastError());
exit(1);
}
while (1)
{
printf(“Listening To Client…\n”);
sockaddr_in client_addr;
int client_addr_len = sizeof(client_addr);
SOCKET m_New_Socket = accept(m_Socket, (sockaddr *)&client_addr, &client_addr_len);
if (SOCKET_ERROR == m_New_Socket)
{
printf(“Server Accept Failed: %d”, WSAGetLastError());
break;
}
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
if (recv(m_New_Socket, buffer, BUFFER_SIZE, 0) < 0)
{
printf(“Server Receive Data Failed!”);
break;
}
char file_name[FILE_NAME_MAX_SIZE + 1];
memset(file_name, 0, FILE_NAME_MAX_SIZE + 1);
strncpy_s(file_name, buffer, strlen(buffer)>FILE_NAME_MAX_SIZE ? FILE_NAME_MAX_SIZE : strlen(buffer));
printf(“%s\n”, file_name);
//打开文件,准备写入
FILE * fp;
errno_t err = fopen_s(&fp, file_name, “wb”); //windows下是”wb”,表示打开一个只写的二进制文件
if (err != 0)
{
printf(“File: %s Can Not Open To Write\n”, file_name);
system(“pause”);
exit(1);
}
else
{
memset(buffer, 0, BUFFER_SIZE);
unsigned int length = 0;
while ((length = recv(m_New_Socket, buffer, BUFFER_SIZE, 0)) > 0)
{
if (fwrite(buffer, sizeof(char), length, fp) < length)
{
printf(“File: %s Write Failed\n”, file_name);
break;
}
memset(buffer, 0, BUFFER_SIZE);
}
printf(“Receive File: %s From Server Successful!\n”, file_name);
}
fclose(fp);
closesocket(m_New_Socket);
}
//释放winsock库
WSACleanup();
system(“pause”);
return 0;
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h>
#define PORT 8087
#define SERVER_IP “127.0.0.1”
#define BUFFER_SIZE 1024
#define FILE_NAME_MAX_SIZE 512
#pragma comment(lib, “WS2_32”)
int main()
{
// 初始化socket dll
WSADATA wsaData;
WORD socketVersion = MAKEWORD(2, 0);
if (WSAStartup(socketVersion, &wsaData) != 0)
{
printf(“Init socket dll error!”);
exit(1);
}
//创建socket
SOCKET c_Socket = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET_ERROR == c_Socket)
{
printf(“Create Socket Error!”);
system(“pause”);
exit(1);
}
//指定服务端的地址
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.S_un.S_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
if (SOCKET_ERROR == connect(c_Socket, (LPSOCKADDR)&server_addr, sizeof(server_addr)))
{
printf(“Can Not Connect To Server IP!\n”);
system(“pause”);
exit(1);
}
//输入文件名
char file_name[FILE_NAME_MAX_SIZE + 1];
memset(file_name, 0, FILE_NAME_MAX_SIZE + 1);
printf(“Please Input File Name On Server: “);
scanf_s(“%s”, &file_name);
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
strncpy_s(buffer, file_name, strlen(file_name)>BUFFER_SIZE ? BUFFER_SIZE : strlen(file_name));
//向服务器发送文件名
if (send(c_Socket, buffer, BUFFER_SIZE, 0) < 0)
{
printf(“Send File Name Failed\n”);
system(“pause”);
exit(1);
}
FILE * fp;
errno_t err= fopen_s(&fp,file_name, “rb”); //windows下是”rb”,表示打开一个只读的二进制文件
if (err!=0)
{
printf(“File: %s Not Found\n”, file_name);
}
else
{
memset(buffer, 0, BUFFER_SIZE);
int length = 0;
while ((length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0)
{
if (send(c_Socket, buffer, length, 0) < 0)
{
printf(“Send File: %s Failed\n”, file_name);
break;
}Sleep(100);
memset(buffer, 0, BUFFER_SIZE);
}
fclose(fp);
printf(“File: %s Transfer Successful!\n”, file_name);
}
closesocket(c_Socket);
closesocket(c_Socket);
//释放winsock库
WSACleanup();
return 0;
}
解决方案
10
有时不将“调用函数名字+各参数值,进入函数后各参数值,中间变量值,退出函数前准备返回的值,返回函数到调用处后函数名字+各参数值+返回值”这些信息写日志到文件中是无论怎么样也发现不了问题在哪里的,包括捕获各种异常、写日志到屏幕、单步或设断点或生成core文件、……这些方法都不行! 写日志到文件参考下面:
//循环向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; }
任何收发两端速度不一致的通讯,都需要在它们之间使用一个足够大的FIFO缓冲区。
对任何FIFO缓冲区的使用,都需要仔细考虑接收端接收时超时无数据和发送端发送时FIFO缓冲区已满这两种情况下该怎么样做。
这些概念都在这段经典代码中有所体现。
这段经典代码还包括以下必须考虑的因素:
◆跨Windows和Linux平台
◆多线程锁
◆多线程日志
◆日志文件占用的磁盘空间可控
◆日志中的时间包括毫秒
◆传输的数据对应的每个字节到底是几
◆怎么样退出多线程程序
◆……
10
抓包,调试。
10
调试任何通信系统,都要先会用对应的抓包工具。本人觉得。
10
建议先确认服务端能否真的接收到客户端发送的信息,然后尝试用fflush函数在每次写文件后刷下。