Uploaded by aza sattarov

CLIENT

advertisement
#include <winsock2.h>
#include <cstring>
#include <iostream>
#include <fstream>
// libwsock32
void PrintErrMsg(const char* fName)
{
std::cerr << fName << " failed: " << WSAGetLastError() << std::endl;
}
int main()
{
std::cout << "Client is running" << std::endl;
WSADATA wsaData;
if(!WSAStartup(MAKEWORD(2, 2), &wsaData))
{
if((2 == LOBYTE(wsaData.wVersion)) && (2 == HIBYTE(wsaData.wVersion)))
{
SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
if(s != INVALID_SOCKET)
{
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(9090);
server.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(s, (sockaddr*)&server, sizeof(server)) != SOCKET_ERROR)
{
std::ifstream ifs("in.txt"); // читает из файла: 2.2 + 4
if(ifs.is_open())
{
char buf[256];
int recvRet(0), recvTot(0);
ifs.getline(buf, sizeof(buf));
if(std::strlen(buf) == send(s, buf, std::strlen(buf), 0))
{
if(shutdown(s, SD_SEND) != SOCKET_ERROR)
{
do
{
recvRet = recv( s, buf + recvTot, sizeof(buf) - recvRet, 0);
} while(recvRet > 0 && (recvTot += recvRet));
(std::cout << "Received " << recvTot << " bytes: ").write(buf, recvTot) << std::endl;
if(0 == recvRet)
{
std::cout << "recv OK\n";
}
else PrintErrMsg("recv");
}
else PrintErrMsg("shutdown");
}
else PrintErrMsg("send");
}
else std::cerr << "Unable to open file\n";
ifs.close();
}
else PrintErrMsg("connect");
closesocket(s);
}
else PrintErrMsg("socket");
}
else std::cerr << "Usable version of Winsock.dll not found\n";
WSACleanup();
}
else PrintErrMsg("WSAStartup");
std::cin.sync();
std::cin.get();
return 0;
}
Download