Thursday, January 28, 2010
Send File from Server to Client using C# Socket Programming
Hi, I will discuss about the code later. For now just the codes.
One small hints, about how this is working - First client try to connect to server. Then in server side, server gets a object of client socket. In past all time by that socket object data was transferred from client to server. But now server sends data to client using same socket. This is just opposite of Client to server file transfer.
Client code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Client_Socket
{
//FILE TRANSFER USING C#.NET SOCKET - CLIENT
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("That program can transfer small file. I've test up to 850kb file");
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
clientSock.Connect(ipEnd);
byte[] clientData = new byte[1024 * 5000];
string receivedPath = "C:/";
int receivedBytesLen = clientSock.Receive(clientData);
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
Console.WriteLine("Client:{0} connected & File {1} started received.", clientSock.RemoteEndPoint, fileName);
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append)); ;
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
Console.WriteLine("File: {0} received & saved at path: {1}", fileName, receivedPath);
bWrite.Close();
clientSock.Close();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("File Sending fail." + ex.Message);
}
}
}
}
Server code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace beginSocketServer
{
//FILE TRANSFER USING C#.NET SOCKET - SERVER
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("That program can transfer small file. I've test up to 850kb file");
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
//clientSock is the socket object of client, so we can use it now to transfer data to client
Socket clientSock = sock.Accept();
string fileName = "test.txt";// "Your File Name";
string filePath = @"C:\FT\";//Your File Path;
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
byte[] fileData = File.ReadAllBytes(filePath + fileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
clientSock.Send(clientData);
Console.WriteLine("File:{0} has been sent.", fileName);
clientSock.Close();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("File Receiving fail." + ex.Message);
}
}
}
}
Labels: .net, c#, File Transfer, Server to Client, Server to Client File Transfer



where to run these codes,,,,can u plz help me with the pocedure,,,thank u.
Hi,
Before reading this article need to read once 'File Transfer using C# Socket'.
This is a console based application. You need to run first Server application then client. This for local host(same machine). If you run in different machine, need to configure once. About server IP/address in client code, file path & folder.
Follow this code will run smoothly.
Thanks,
Suman
This worked fine on Firefox. But not on IE8. I saw a reference to a header "Accept-Range" on another post, but not sure if this has anything to do with my problem. Furthermore, I was wondering if you can provide more details on structuring this data (with the embedded name and length)...is this arbitrary or is there other compatible information that can be stored in the file before transmission. I think these embedded values may be the key for getting it to work on IE.
Hi,
This is not for Web Application. This is for Console/Windows application. Try it in these type of application.
Thanks,
Suman
when i run it tell me that the file access path is denied so it does send it but the computer does not let the file to be written to it would you help me with this?
Hi Ale,
Your problem is not clear to me totally. Please tell me quite more about that problem with some code references.
Suman
where to change the ip address in ur code...i am new to socket programming plz help
Hi,
Search 'Your File Name' then put your file name and next line file path put there your folder name.
Suman
hai
i am using your code in same machine its threw a exception.because client cound not connect to the server,Next i am used to LAN also its same problem
This error is given below "
An address incompatible with the requested protocol was used ::1:5656"
Hi,
Not clear to me about the problem, but seems to me it is happening due to wrong IP address like for localhost 127.0.0.1.
Please check these and let me know the result.
Thanks,
Suman
"wrong IP address like for localhost 127.0.0.1."
i have the same problem. I tried the lan ip of the computer 192.168.. instead of localhost but i've got the same exception again.
I had did a test on this. It is working though (WAN). I able to send file to my friend by modifying the code as what Suman has said "About server IP/address in client code".
But my comp is refusing the port when I am the server(from debug mode), while my friend is the client who connect to me.
this case is different when my friend is the server, I m the client who connect to him. I did a successful test, in other word the file transfer is complete.
So this means my comp itself refusing the port. Anyway to solve this?
Thx in advance. I am willing to share the successful test solution file(visual studio 2008) if anyone here need.
Hi ALien_13,
Your testing steps was like this,
First, your computer set as Server and your friend client. Next time your friend Server you client. Again next you server your friend client, and getting problem?
If yes, that means in your computer Server code still running in background so it can't create new server with the same port.
For that problem you need to end the process from 'Task Manager' or you can restart your computer.
If it was not the way of testing then this cause may be your firewall settings.
Test once and reply please.
Regards,
Suman
Hello sir.I tried ur small file tranfer code bt evrytime it gives different size of same file after tranfering.and aalso i wnt to tranfer file upto 100MB.How can i change ur codePlese Reply.
Hi Kalyani,
I don't know exactly if there has any bug or not, however I will check this code once again.
You can transfer large file from Server to Client by following few steps.
First slice the file, and then transfer these slices.
To do these steps you may follow my other articles. 'Send 2GB file from Client to Server' this will help you a lot.
Thanks,
Suman
Sir,I m trying ur 4GB program bt i dont understand how to run it.I transferd 30MB size file using ur small size file coe(850kb)bt at client side it has size 0 or somtimes 4.88Mb.I want to tranfer .exe from server to client.How can do?
Suman, can we combine both your apps into a single program? I mean, the file transfering happening on both sides: where there is a server running on a remote machine and client running on a local machine and the client is able to send a file first to the server and later the same app is able to receive a file from server: Server->Client and Client->Server in the same program synchronously...
Thanks,
Srikanth
good Article
File Sending Failed.An exiting Connection was forcibly closed by the remote Host. :(
I am using this code on same machine,,both server n client,,,
My scenario is that Client send file name to Server and Server look for the Requested File and than send it back to the Client.
Can U plz help me ,,,,
Thanks in Regard
Hi MSalman Ali,
Probably your server application stopped or it can not open the port. Check your program if it is running properly and able to open the port or not with same port number for client and server.
Thanks,
Suman
Its is nice information about socket program,and also i need heartbeat application basic like u given socket programe,
I am expecting response from u suman ,
Thanks for posting such good article about SocketProgramming
Hi Shravan,
I did not get you.
Thanks,
Suman
Hi,
should server be Public IP for the following code u have given?
Hi,
For intranet(LAN) not required but internet it is required.
Thanks,
Suman
Hi Suman,
I am new in socket programming, wrote one server socket application.
Here i cannot put all code, therefore just putting some codes.
Socket clientSocket = serverSocket.Accept();
The above clientsocket i need to close on another function.
In that function clientsocket is calling as object. please see code
static void ThreadProcess(object clientSocket)
But i cannot close clientsocket inside this funtion.
Please help me, i can give u complete code if u give your email id.
Thanks Suman
Hi,
I am not sure about that problem. Seems there may 2 things may happen.
1. You are not releasing all resources which are associated with that socket object. Need to release these first.
2. Check thread id of calling function and called function, means where socket object are created and where socket are trying to close. If both are same then it is difficult to say what is the exact problem (then may i need to check code) but if these two thread are different (id) then you have to close socket in same thread where it is starting.
Thanks
Suman
Thanks for reply.May be i am confusing you, but try to explain little more, please have a look below
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, g_port);
Socket serverSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(localEndPoint);
serverSocket.Listen(int.MaxValue);
Console.WriteLine("Ready to receive clients...");
Socket clientSocket = serverSocket.Accept();
WaitCallback workitem = new WaitCallback(ThreadProcess);
}
if i write clientsocket.close inside above function, after that while debugging application will come to end of following code
saying i already closed.
static void ThreadProcess(object clientSocket)
{
StreamReader reader = null;
StreamWriter writer = null;
NetworkStream networkStream = new NetworkStream((Socket)clientSocket);
byte[] bytes = new byte[1025];
Int32 i = networkStream.Read(bytes, 0, bytes.Length);
string clientMessage1 = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
......
}
Becuase of above mentioned error i tried to write code for closing clientsocket above function but didn't found
close method, only found equals,gethashcode,getType,ToString.
This is the problem i am facing.
This comment has been removed by the author.
i m trying to run this program but i get an error that "file sending fail.an address incompatible with the requested protocol was used [::1]:5656"
all i m doing is changing the file name and file path in the server code
thats it
i m not changing anything on the client code.
pleaseeee help
i m waiting for ur reply suman
hi, please help me these code with what use program?
Hi Maryam,
I am not clear about your question. If you want code of that program then just copy and paste from the article.
Thanks
Suman
i aplogize from the fact my english is not too good,
i mean , this environment can be tesed in that program?
anither thing , this program only in case the LAN network can be tested?
this piece of code for chat program is a double?
i am waiting for reply
Hi Maryam,
You can test this code in LAN and WAN (internet) both.
Suman
Hi Suman,
Your Article on Server/ Client is helpful.Do u have any sample file transfer program using muticast. Any Help on this would be great.
Hi,
Sorry still I do not have any ready made code for this purpose. Please continue to visit my blog I have planning do same in future. Thanks for your comment and visit to my blog.
Suman
hi sir,
I have an error while running your code ie., first it display like this
"server started to received" after some time it display file sending failed"-in code the compiler does not compile this code" bwrite.Write(clientdata, 4 + filenamelen, receivedbytelen - 4 - filenamelen); Why it was happened?
"this is the error in client side and in server side it just running but no response from it,it takes more time to response.
this is my mail id "bsiva.nathan88@gmail.com"
Pls reply me to this id..
and how to run this code...
Hi Siva,
Still you are getting same problem? Or any other person getting same type problem, please reply.
Thanks
Suman
This comment has been removed by the author.
This comment has been removed by the author.
Paras's request was like that:
hi suman i read all comments
Actually i am working on one program that download data from web and save it to another computer
i done downloading part but not able to do save part
and i read ur program it working fine if it run on one pc but it not working on another pc
i understand that do changes in ip/address in client class i changed some ip address but it generate error
if u able to give some hint or help
plz reply i am waiting........
Hi Paras,
I see your request but I was busy so I can not reply you immediately, also this can't possible to me reply so promptly.
But Paras you are trying to use that code for Web Application, but this code can work on only in desktop or Windows environment not in Web environment. So you are getting error.
- Suman
Solution for error : "file sending fail.an address incompatible with the requested protocol was used [::1]:5656"
Take server code and change IPAddress.Any to IPAddress.LoopBack
Then tkae client code and change Dns.GetAddress("localhost") to GetAddress("127.0.0.1").
This works fine in windows7
hi suman i used ur code
but server receive some of the data
actually i sent 112 kb of data but it receive only 80kb or some time it receive 25 kb
i used ur same code on one pc but it has some problem
plz reply on this
Hi Paras,
I don't know surely if there exists any bug in code or not. But this type of problem comes for file slicing and sending slice to destination. Please debug the code if it can send and save last slice or not. May be problem is exists there.
For your testing you can reset slice data size (for slice and send) to different size.
- Suman
Can u help to remote webcam control by c#?
Hi,
This code is for console applications.Can u please help me in transferring file in web application also???
This comment has been removed by the author.
hi Suman
your code is helping me a lot
bt i am getting error
"File Sending fail.No connection could be made because the target machine actively refused it 127.0.0.1:5656"
please help thank you in advance
Hi,
Seems you have not run Server Application first.
First run your server application then try to connect from client application. Server application IP and port must be correct otherwise same problem will come.
Regards,
Suman
Hi Suman,
Thanks alot for this code,but can you change this to Windows form application.I mean that a form for server that have "Send to","Browse file" button etc. and a form for client that have "save to" button etc.And then make two .exe file that run without opening your project.Please help me!
Thanks.
(sorry if my English is bad)
hi im john.... remem...?
one help..
i need simple TCP socket program using Applet in java.. i tried i is nt working.. if u can, send 2 me..
thnks..
bye
sorry john i never have worked in Java i can't help you
Suman
hi,
I working on build such application but I want to add some extra properties, anyway the problem that I am facing right now is that I can't send a file of any type unless I set that extension within the code.
I want to let the client send file of any type (.jpg, .avi, .exe, ...) however I will share this part of my code with you hopefully you have something to advise me with.
Stream fileStream = File.Create("F:\\nf\\receive");
// fileStream.GetType();
while (true)
{
thisRead = networkStream.Read(dataByte, 0, blockSize);
fileStream.Write(dataByte, 0, thisRead);
if (thisRead == 0) break;
}
the main problem I NEED TO ADD THE EXTENSION TO THE FILE AFTER THE SERVER RECEIVES IT SO THE SERVER WILL NOT ASK THE USER ABOUT WHICH APPLICATION SHALL THE USER USE TO OPEN THE FILE.
REGARDS,
Hayder
That's very nice man. But i have do to File transfer using c# http protocol , plz tell some idea abt that ..
File transfer will be missed
Will how only then not omit the reference material
Eidson
I am very like this posting, waitng for next..pls keep continue new posts.
http://mlmdevelopers.com/products/mlm-software/corporate-mlm-software/feature.html
Hi All,
Does this code work in Unix server or not ?
Probabaly will not work, but you can try with Mono project, but I am not much aware about it.
.Net is for Windows only mono-project is trying to develop it with different OS. Can try once
Suman
hi,
first of all thanks for this post it's really helpful
I have one question considering encryption ! if I want to add like AES for example to the process , where to use the encrypt method in the sender so the file get encrypted before being transferred , and how can this method handel the data file ?
same thing goes for the server side in decryption .
assume the enc/dec method are working well as in MSDN AES crypto service provider example code .
thanks alot
best regards
Katia
Hi
After a long gap really I received a good qustion so respoding asap even from mobile.
You have to encript your data before sening it. You will get a section from where file reading by binary IO stream. It is doing by loop and reading data in only few kb and placing to send it to server. Before sending this data call your encription function which will get the file data and return encripted data. The send this encripted data to server. I think you need change 2/3 lines of code to do it.
At server side there has similar type of code from where data is reading from client using a socket object and next it is saving in file using IO stream. So you have to placed your decription code here by similer way and change will be done withvery little code change.
Hope this will work, if you need any more help pls ask me.
Regards
Suman
Hi
After a long gap really I received a good qustion so respoding asap even from mobile.
You have to encript your data before sening it. You will get a section from where file reading by binary IO stream. It is doing by loop and reading data in only few kb and placing to send it to server. Before sending this data call your encription function which will get the file data and return encripted data. The send this encripted data to server. I think you need change 2/3 lines of code to do it.
At server side there has similar type of code from where data is reading from client using a socket object and next it is saving in file using IO stream. So you have to placed your decription code here by similer way and change will be done withvery little code change.
Hope this will work, if you need any more help pls ask me.
Regards
Suman
Hi suman Biswas ..thank you for your project...what i am really not able to know is that this project only works for a single system...that is both client and server running on same system...but how can i be able to transfer files to server running on other system with different IP Address...please let me know as it is very urgent for me....Thnak you
hi Suman ....can you please tell me how to configure server Ipaddress in client code so that i can send files to the server....thank you waiting for your reply....
really good ...
Thanks....
Hi
Check there has a section where IP End point is binding. Probably in code it has written with localhost, if you put there any IP address then it will work, but be sure this address is reachable , means it can get throught Ping
Suman
This comment has been removed by the author.
hi suman thank you, it really works.......thank you very much...you have just saved my job.....i have another question how will you communicate back to the client i mean we are only sending data(file) to server but not back to client how can we make it possible in both ways.....can you please help me...(Client-server-client)
Hi
It is great news that my code has helped you. Your expected thing can possible by this code but you need to modify it. Check in code there has some section is sending data from server to clinet, basically it is happenibg to send notification to client about how much data it has received. You also can develop this . For that you have to follow these steps (1) open a server socket (2) open a client socket and connect to server (3)read and send data from server to client. It is similer like these code difference only to send data from server socket to client and client will receive it and save to local disk. You will get a problem about synchronization between data receive and send in server program. You have to control these acticity carefully in server. Try it ....it will work.
You can send a gift to me by clicking on these adds. :-)
suman
hi suman thanks for your explanation......actually i am working on gprs data.... i will be getting latitude and longitude values continuously(with a time gap of 1 sec) and i should save this data on to a text file(In your project we are directly sending and saving text file).... is it possible to make some changes to this code so that it will work for my project
Hello Maheedhar,
Yes you develop your project based on my code, I do not have any problem for that.
But I will be happy if you can share this information in that blog that, your project is using this code. I am asking this because next time other people can get more confidence to use this code in their project.
Thanks for informing,
Suman
Thank you suman i will do that.but you have not answered my question.How can we store data directly on to a text file instead of sending files.Can you please help me.i will be very thank full to you.i am an ECE student and don't have any idea about .NET
Hi
You do not have idea about .Net and you are trying to develop something with most critical part of .Net!
But I am not understood your question, sending file and store to text file what is difference? If you can get binary data then you can save to any file using Binary Stream.
Suman
hello,
can u pls tel me how to do a client server application using forms in c#?
Hi
I believe there has an application with win forms and dll of this code from there you can get and idea
Suman
Hi Biswas,i just made some modifications to your code so that i can tranfer the same file repeatedly to the server....actually it shows no errors during the build project but when i am running the programme the client code gets struck...can you please suggest some modifications.
thank you.
Hi
I dont know how u have written your code about to send file multiple time. It seems to me client is getting deadlock during sending file multiple time.so it might be reason may be any reason can give this problem
Suman
In this code IPAddress is getting atomatically.help me to enter IPAddress manually while writing code.(i just wana use code in 1 system only)
leave a response