0
点赞
收藏
分享

微信扫一扫

C++txt文件传输 下


这个是发送端。

思路:

文件小就1次传。大了就分开传。

.h

#define _WINSOCK_DEPRECATED_NO_WARNINGS 
#ifndef _H_H__
#define _H_H__
#include <iostream>
#include <WinSock2.h>
#include <string>
#include <fstream>
#include <thread>
#pragma comment (lib,"ws2_32.lib")
using namespace std;

class C
{

public:
C();
~C();
static void readfr();


};
#endif //_H_H__


cpp

#include "h.h"
SOCKET s;
C::C(){

WSADATA wsadata;
WORD v = MAKEWORD(2, 2);
if (WSAStartup(v,&wsadata)==-1)
{
exit(0);
}
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(4567);
sin.sin_addr.S_un.S_addr = inet_addr("192.168.1.3");
int n = sizeof(sin);
if (::connect(s, (SOCKADDR*)&sin, n) == -1)
return;
thread t(readfr);
t.detach();


}
C::~C(){

WSACleanup();
}
void C::readfr(){
char buf[255];
int can = 256;
int n;
int used= 0;
int R = recv(s, buf, 256, 0);
buf[R] = '\0';
cout << "Get "<<buf << endl;
ifstream in("1.txt", ios_base::binary | ios_base::in);
if (!in.is_open())
{
cout << "Open Fail" << endl;
return;
}
in.seekg(0, ios::end);
n = in.tellg();
in.seekg(0, ios::beg);
cout << n << endl;
if (n<can)
{
char buff[255];
in.read(buff, n);

::send(s, buff,n, 0);
cout << "send over" << endl;

in.close();
R = ::recv(s, buff, 256, 0);
return;
}
int num = 0;
while (n>0)
{
if (n >can)
used = can;
else
used = n;
n -= used;
char * buff = new char[used];
in.read(buff, used);
::send(s, buff, used, 0);
cout << ++num << endl;


R = ::recv(s, buff, 256, 0);
delete buff;
if (R<=0)
{
break;
}
Sleep(1);
}
if (in.is_open())
in.close();
closesocket(s);

}

int main(){

C c;
system("pause");
}




举报

相关推荐

0 条评论