You are on page 1of 11

http://www.scribd.

com/doc/15646254/C-Balaguruswamy-Solved-Programs
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
Suman Biswas | 80 comments | # |

S E N D

F I L E F R O M S E R V E R T O C L I E N T C # S O C K E T P R O G R A M M I N G

U S I N G

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
This entry was posted by Suman Biswas, on Thursday, January 28, 2010. You can leave your response.

1.

8 0 C O M M E N T S BETABAAG | FEBRUARY 1, 2010 7:39 AM | where to run these codes,,,,can u plz help me with the pocedure,,,thank u.

2.

SUMAN BISWAS | FEBRUARY 1, 2010 8:39 AM | 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 3. GEOMAGNET | FEBRUARY 4, 2010 12:30 PM | 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. 4.
SUMAN BISWAS | FEBRUARY 4, 2010 9:21 PM |

Hi, This is not for Web Application. This is for Console/Windows application. Try it in these type of application.

Thanks, Suman 5. ALE | FEBRUARY 9, 2010 10:17 AM | 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? 6.
SUMAN BISWAS | FEBRUARY 9, 2010 9:15 PM | Hi Ale, Your problem is not clear to me totally. Please tell me quite more about that problem with some code references.

Suman 7. SUKUMAR | FEBRUARY 17, 2010 4:56 AM | where to change the ip address in ur code...i am new to socket programming plz help 8.
SUMAN BISWAS | FEBRUARY 17, 2010 8:12 PM | Hi, Search 'Your File Name' then put your file name and next line file path put there your folder name.

Suman AMUL | FEBRUARY 22, 2010 1:05 AM | 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" 10. SUMAN BISWAS | FEBRUARY 22, 2010 1:17 AM | 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. 9. Please check these and let me know the result. Thanks, Suman 11. EREN | MARCH 1, 2010 2:02 PM | "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. 12. ALIEN_13 | MARCH 9, 2010 10:27 AM | 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. 13. SUMAN BISWAS | MARCH 10, 2010 12:55 AM | 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 14. KALYANI | MARCH 31, 2010 9:54 PM | 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. 15.
SUMAN BISWAS | MARCH 31, 2010 10:20 PM | 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 16. KALYANI | MARCH 31, 2010 10:39 PM | 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? 17.
SRIKANTH | APRIL 16, 2010 11:57 AM | 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 18. SANDEEP | MAY 10, 2010 11:53 PM | good Article 19.
MSALMAN ALI | MAY 11, 2010 3:24 PM |

File Sending Failed.An exiting Connection was forcibly closed by the remote Host. :( 20.
MSALMAN ALI | MAY 11, 2010 3:30 PM | 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 21. SUMAN BISWAS | MAY 15, 2010 2:34 AM | 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 22. SHRAVAN | JUNE 5, 2010 4:11 AM | 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 23. SUMAN BISWAS | JUNE 7, 2010 12:32 AM | Hi Shravan, I did not get you. Thanks, Suman 24. ASHU959 | JUNE 29, 2010 2:42 AM | Hi, should server be Public IP for the following code u have given? 25. SUMAN BISWAS | JUNE 29, 2010 4:19 AM | Hi, For intranet(LAN) not required but internet it is required. Thanks, Suman 26. JOSH | JULY 12, 2010 5:12 AM | 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 SUMAN BISWAS | JULY 12, 2010 5:27 AM | 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.

27.

Thanks Suman 28. JOSH | JULY 12, 2010 5:55 AM | 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); ...... }

You might also like