Click here to Skip to main content
6,292,426 members and growing! (10,276 online)
Email Password   helpLost your password?
Languages » C / C++ Language » General     Intermediate

C++ Winsock Client To Server File Transfer - Made Easy

By kbfromindia

Easy way implement winsock c++ code for file transfering.
C++, Windows, Visual Studio, Dev
Posted:3 Apr 2006
Updated:23 Aug 2006
Views:76,357
Bookmarked:27 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
21 votes for this article.
Popularity: 3.52 Rating: 2.66 out of 5
9 votes, 42.9%
1
2 votes, 9.5%
2
1 vote, 4.8%
3

4
9 votes, 42.9%
5

Sample Image - WSFileTransfer.jpg

Introduction

I was searching for a file transfer program using winsock with tcp and udp. I found some code which are complex and most of them are MFC based. So problem was to convet it to a Non-MFC based program.

Another point is, the code should also be compatible with Linux sockets sys/socket.h
All my code functions is compatible to Gnu's gcc compiler except some error handling part.

I had found most project here are quite complex to understand for beginner like me. So, I collected easy examples specially from MSDN and created a simple project.

It is so simple - That people will say - its just a damn child code. Nothing more than that.

I have avoided writing many comments, so its easy to see the code steps. This is wrong I know, but this is the way I write programs. I am also very lazy to do such things.

Gradually I will comment all my codes.

This is a program which has implemented Winsock 2.0 - has a utility class WComm which has very simple methods to create client/server program as well as File Transfer Utility.

Implementation

Given below are very simple steps in very simple words to start with a client/server winsock application with winsock.

Creating VC++ Project

  • Open a new windows console project.
  • Add the wcomm.cpp and wcomm.h files to it.
  • Add ws2_32.lib to Project Settings -> Link -> Object/library modules.

The Server

  • Just call startServer(port_no) to start the server at port_no
  • waitForClient() method waits for a new client and exists the function when a new client connects.
  • recvData(rec_buffer,buffer_size) receives character array sent by client. It return value is the number of bytes sent. If its -1, it means connection is closed.
  • sendData(send_buffer) sends character array to client. It retuns the number of bytes sent to client.

The Client

  • connectServer(ip_addr,port) connects the server at ip_addr at the given port
  • sending and receiving are similar to that of server.

File Transfer

  • On client side: There are 2 steps to be followed.
    1. SEND/RECEIVE Command Pair To Inform Server To Be Ready. Example:
      w.sendData("FileSend");w.recvData(rec,32);
    2. Call the File Send Command fileSend(absolute_file_fpath)
  • On server side: Call fileReceive(fname). The file is saved where the server is running and the filename is known from passed fname char[] argument.

Important Note

  • After each sendData, there has to be a recvData and after each recvData, there has to be a sendData for smooth transfer of data.
  • Please implement all the error checks as far as possible. I have avoided it - to make the codes more readable. Also Refer to Winsock MSDN Reference. There is Windows Sockets Error Codes link. Use WSAGetLastError() To find last winsock related errors. Socket errors are vital and should be handled nicely.
  • I have use direct numeric values instead of #define constants in most places. According to your ways, use Find-Replace to replace with some nice constants.

Sample

This sample project has a main program which implements both client and server according to the argument passed.

In the server code, there is a loop which listens for a client and when it gets the client connection, it moves to another loop - where it gets the client responses.

Client code is very simple - just connects to data, sends,receives, and ends.

Actually everything is very simple. One might see that the code is not good in error handling. This is because - its just made to make it more readable. This is the starting point. Now go ahead and implement whatever you want with it.

Sample Main.CPP From Src

#include "wcomm.h"



void runclient(char *ip, char *fpath);
void runserver();

WComm w;

void main(int argc, char *argv[])
{
	if(argc==1)runserver();
	else runclient(argv[1],argv[2]);
}


void runserver()
{
	// Start Server Daemon

	w.startServer(27015);
	printf("Server Started........\n");
    while (TRUE) {
		// Wait until a client connects

		w.waitForClient();
		printf("Client Connected......\n");

		// Work with client

		while(TRUE)
		{
			char rec[50] = "";
			w.recvData(rec,32);w.sendData("OK");

			if(strcmp(rec,"FileSend")==0)
			{
				char fname[32] ="";
				w.fileReceive(fname);
				printf("File Received.........\n");
			}
			if(strcmp(rec,"EndConnection")==0)break;
			printf("Connection Ended......\n");
		}
		// Disconnect client

		w.closeConnection();
	}
}

void runclient(char *ip, char *fpath)
{
	char rec[32] = "";
	// Connect To Server

	w.connectServer(ip,27015);
	printf("Connected to server...\n");
	// Sending File

	w.sendData("FileSend");	w.recvData(rec,32);
	w.fileSend(fpath);
	printf("File Sent.............\n");
	// Send Close Connection Signal

	w.sendData("EndConnection");w.recvData(rec,32);
	printf("Connection ended......\n");
}

Hope you will do much better than what I did.... :-)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

kbfromindia


Member
Hi, I am a simple programmer and try to make things as simple as possible.

I code in c++, vb, perl etc. and try making simple objects out of things which look very hard
Occupation: Web Developer
Location: India India

Other popular C / C++ Language articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh)FirstPrevNext
Generallong filenames gives error to client and freezes server PinmemberOwynTyler4:24 2 Jun '09  
Generalcan't compile, can't compile useing your lib in mode other than /MTd PinmemberOwynTyler9:07 31 May '09  
GeneralPlease help Pinmemberjohannes_dj9:23 18 Feb '09  
GeneralRe: Please help Pinmemberharriccane5:15 11 Jun '09  
Generallinker error Pinmembervidit.iitr11:08 11 Mar '08  
GeneralI no longer spent time here Pinmemberkbfromindia0:31 31 Aug '07  
GeneralRe: I no longer spent time here PinmemberMember 38637684:04 6 Dec '07  
Questiontransfered files Pinmemberzen.Ben15:23 27 Jun '07  
Generalerror C3861: 'atoi': identifier not found [modified] Pinmemberesia9:36 20 Apr '07  
Generalhelp me wid my project Pinmembermuzamil_mlore0:36 30 Mar '07  
Generaluse it in MFC Pinmemberlplover2k21:13 29 Mar '07  
GeneralJust what I was looking for.. Pinmembertrojandj20:18 27 Mar '07  
Generalgood post hard to work out Pinmemberkarlx1:41 6 Jan '07  
QuestionConverting the program to a library PinmemberPranav Lal22:56 22 Aug '06  
AnswerRe: Converting the program to a library Pinmemberkbfromindia2:45 23 Aug '06  
GeneralRe: Converting the program to a library PinmemberPranav Lal19:37 23 Aug '06  
Generalsuch a nice code Pinmembertiki3:44 24 Jul '06  
GeneralMoron PinmemberDarka23:37 3 Apr '06  
GeneralRe: Moron PinmemberDarka23:48 3 Apr '06  
GeneralRe: Moron Pinmemberkbfromindia23:59 3 Apr '06  
GeneralRe: Moron PinmemberDarka0:08 4 Apr '06  
GeneralRe: Moron Pinmemberyafan19:18 4 Apr '06  
GeneralRe: Moron PinmemberDarka21:52 4 Apr '06  
GeneralRe: Moron Pinmemberyafan13:23 5 Apr '06  
GeneralRe: Moron Pinmembersk8er_boy2873:04 13 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Aug 2006
Editor:
Copyright 2006 by kbfromindia
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project