#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 4096
#define DEFAULT_PORT 8000
int main(int argc, char* argv[])
{
if(argc == 1)
{
printf("Please Input the Address of Input File!\n");
return 0;
}
//Buffers
int recvbuflen = DEFAULT_BUFLEN;
char sendbuf[DEFAULT_BUFLEN];
char recvbuf[DEFAULT_BUFLEN] = "";
//FILE
FILE* file = fopen("C:/1.txt", "rb");
if(file == NULL)
{
printf("Failed to open Input File!\n");
return 0 ;
}
while(1)
{
//SOCKET
//----------------------
// Declare and initialize variables.
int iResult;
WSADATA wsaData;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(1,1), &wsaData);
if (iResult != NO_ERROR)
{
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
SOCKET ConnectSocket;
struct sockaddr_in clientService;
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, 0) ;
if (ConnectSocket == INVALID_SOCKET)
{
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
continue;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientService.sin_port = htons( DEFAULT_PORT );
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) ) ;
if (iResult == SOCKET_ERROR)
{
printf( "connect failed with error: %d\n", WSAGetLastError() );
closesocket(ConnectSocket);
WSACleanup();
continue;
}
while(1)
{
fread(sendbuf, DEFAULT_BUFLEN, sizeof(char), file);
if(feof(file))
{
printf("Reading to the end of input file, seek to the beginning of File!\n");
fseek(file, 0, SEEK_SET);
}
//----------------------
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, DEFAULT_BUFLEN, 0 );
if (iResult == SOCKET_ERROR)
{
printf("send() failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
break;
}
else
{
printf("Send package size = %d \n", iResult);
}
}
if (iResult == SOCKET_ERROR)
{
continue;
}
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ConnectSocket);
WSACleanup();
}
return 0 ;
}