📄 comm.cpp
字号:
#include "Comm.h"
WSADATA wsaData;
SOCKET m_socket;
sockaddr_in con;
WComm::WComm()
{
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR )
printf("Error at WSAStartup()\n");
m_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( m_socket == INVALID_SOCKET ) {
printf( "Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return;
}
}
int WComm::connectServer(char *ip,int port)
{
con.sin_family = AF_INET;
con.sin_addr.s_addr = inet_addr( ip );
con.sin_port = htons( port );
if ( connect( m_socket, (SOCKADDR*) &con, sizeof(con) ) == SOCKET_ERROR) {
WSACleanup();
return 0;
}
return 1;
}
//接受数据函数
int WComm::recvData(char *recvbuf,int size)
{
int sz = recv( m_socket, recvbuf, size, 0 );
recvbuf[sz] = '\0';
return sz;
}
//发送数据的函数
int WComm::sendData(char *sendbuf)
{
return send( m_socket, sendbuf, strlen(sendbuf), 0 );
}
void WComm::fileSend(char *fpath)
{
char rec[32] = "";
// extract only filename from given path.
char filename[50] = "";
int i = strlen(fpath);
// find the last \ in the fpath
for( ; i>=0; i--)
if(fpath[i-1] == '\\' || fpath[i-1] == ':' )
break;
// copy the filename from the fpath
for(int j=0; i<=(int)strlen(fpath); i++)
filename[j++] = fpath[i];
// create an ifstream with fpath and get the size of the file
ifstream myFile(fpath, ios::in|ios::binary|ios::ate);
int size = (int)myFile.tellg();
myFile.close();
// change the (int)size to (string)size
char filesize[10] = "";
itoa(size, filesize, 10);
send( m_socket, filename, strlen(filename), 0 );//给服务器发送文件名称
recv( m_socket, rec, 32, 0 );//接收服务器的返回信息
//send filesize to the server
send( m_socket, filesize, strlen(filesize), 0 );//给服务器发送文件长度
recv( m_socket, rec, 32, 0 );//接收服务器的返回信息
FILE *fr = fopen(fpath, "rb");
long size_backup = size;
int last_number = 0;
printf("===========================Progress=========================\n"); // 60 characters
for(i=0; i<last_number; i++)
printf("-");
while(size > 0)
{
char buffer[1030];
if(size>=1024)
{
fread(buffer, 1024, 1, fr);
send( m_socket, buffer, 1024, 0 );
recv( m_socket, rec, 32, 0 );
int all_number = int((1-(1.0*size)/size_backup)*60);
for (i=0; i<all_number-last_number; i++)
printf("-");
last_number = all_number;
}
else
{
fread(buffer, size, 1, fr);
buffer[size]='\0';
send( m_socket, buffer, size, 0 );
recv( m_socket, rec, 32, 0 );
j=size/4;
for (i=0; i<60-last_number; i++)
printf("-");
}
size -= 1024;
}
printf("\n============================================================\n"); // 60 characters
fclose(fr);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -