Hello Friends, after long day’s
gap I am writing some blog for you. During this time many things has changed in
technological world like earlier I write code with VS 2008 and now VS 2012 has
released. Also lots of changes in our life too. I believe this time I can write
my blog with better English than earlier, which will help you to read this. Ok
lets read this post about to learn new thing which is about to send small file
from server to client. This is just opposite of sending file from client to
server. This is the basic of large file transfer, later I shall use the same
thing to send large file from server to client and finally will use both
(client to server and server to client) large file transfer code client to
client. I shall come to that point step by step.
To send file from server to client need to follow below steps as describe in table by client and server:
File Transfer from Server to Client
To send file from server to client need to follow below steps as describe in table by client and server:
File Transfer from Server to Client
Server
|
Client
|
1. Server creates an IP End Point and a socket object
then bind socket object with IP end point and sends it to listen mode for
incoming client request.
4. Server
receive client request and accept it. Once connection established, server
create another socket object which will handle this client all requests until
connection ends. Client will be informed internally by TCP about connect success.
6.
Prepare
byte data from file which will be sent to client.
7. Server starts sending
byte data over connected socket.
12. Once data transfer
complete and client closes socket connection, server also close server socket
object.
13. Server program work ends here.
|
2. Client creates an IP End Point and a socket object.
3. Try to connect to server using client socket by help
of IP end point.
5. Start preparations
to store incoming byte data from server.
8. Client receives file byte data along with file name
and stores it in byte array.
9. Client retrieve file name from byte data.
10. Client opens a binary stream writer with file name
to store byte data in it.
11. Once file save complete client closes binary stream
writer and server socket objects.
14. Client program work ends here.
|
To send file from server to
client there must be two applications that is Server application and client
application. In code I have mentioned these two parts individually. In below
section I am describing Server action means server application is working and
you need to check server code, for client action need to check client code.
Handshaking of these two socket programming applications should be following:
1) Server Action: First need to run server application, this server application will open
an endpoint with predefined IP address and port number and will remain in
listen mode to accept new socket connection request from client.
It’s just like some one is
waiting at some fixed position to reply on some ones request.
This below section of code
from server application is doing exactly same thing:
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);sock.Bind(ipEnd);sock.Listen(100);
Here line no 1 is creating
an ipEnd point with port number 5656 and IP is local machine IP address. Port
number can be anything except well known port number (port number should be
more than 1024).
Next two lines are creating
a socket object and binding with previously created IPEnd point.
Last line is sending newly
created socket object to listen mode to accept new connection request from
client.
So you need to run server
application first and then client application.
2) Client Action: Now
turn is coming to client to request server.
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);
These codes are from client
application, here first two lines are using to get Localhost IP address and by
using this creating new IPEnd point. Be sure there IP address and port number
must be same as server address. I am running my applications in same machine so
using localhost.
Next two lines of code is
creating a socket object and trying to connect by using IPEnd point. So this
socket object will try to connect server socket which was in listen mode.
3) Server Action: Again
turn comes to server about to response on client’s request and this is doing by
below line of code in server application:
Socket clientSock = sock.Accept();
This “sock” is server socket
object which was created previously and it was in listen mode. This sock object
will accept client request and generate a new socket object with name
“clientSock”. Rest all work in server side will be performed by “clientSock”
object to handle this particular client request.
4) Server Action: These codes are not directly related with socket programming. This is using to read and send file to client.
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);
These lines of code reading some
particular file from local drive and string its data in byte array
“clientData”. File data need to store in array with raw byte format to send
these to client. With data file name size string at initial of file data. This
is predefined between client and server and it needs to do, otherwise client
will not get file name which is sending by server.
For my case I am using first four
byte to represent file name length and form 5th byte file name is storing. So all file
data will store after file name.
5) Server Action: Now file data is in byte array and it needs
to send to client. The same thing is happening by using below code with the
help of client socket (clientSock) object, which was created during client
request acceptance.
clientSock.Send(clientData);
Basically server application task
ends here for small file transfer. Remaining code has used for some decoration
and socket closing related things.
5) Client Action: Now again turn comes to client and it will
perform below tasks:
byte[] clientData = new byte[1024 * 5000];
string receivedPath = "C:/";
int receivedBytesLen = clientSock.Receive(clientData);
Here first two lines are just
creating byte array to store server data and path is used to decide where data
to be save. In my code, I am saving data in C: drive.
Last line is start receiving data
from server. Whenever client socket starts receiving server data then it
returns length of data which has captured in a integer variable.
6) Client Action: This
section of code is retrieving file name length and by using this file name
which was sent by server at the starting of file data. This will require
retrieving file name.
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
7) Client Action: Now received data is saving at client side by
using below lines of code with the help of binary stream writer.
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append));
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
Here file data is starting to
retrieve after file size and file name bytes. This has managed in 2nd line.
By that way one small file can be
sent from server to client.
8) Client and Server
Action: Now server and client both will do same activity; that is to
release server and client socket by using close method of socket. Client needs
to close binary stream writer as well.
So by following these steps a
file can be sent from server to client. Same way we can send large file from
server to client. TCP buffer can not handle large data size at a time. So if
you try to send large file it will throw overflow error. To avoid this error
you need to slice big file in small pieces (same thing has applied in 2GB file
transfer article) and need to send one by one slice. So there will be loop to
send file from server to client that means step 5 to step 7 will repeat.
Also server can send some
particular file based on client request. But for that client need to send file
name at the time of server request. So server can search file based on this
information, so can read and send particular file to client.
By handling multiple clients
objects one server can send file to multiple clients simultaneously but for
that you need to create multithread application and need to keep track client
socket object array with data file. So programming must be more complex. I am
planning to write codes up to multiple client to client large file transfer
with the help of one server application step by step. So keep watching my blog
to learn new things.
Download this project from below
link:
Full codes are here...
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 - CLIENTclass 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 codes are here...
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 - SERVERclass 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 clientSocket 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);}}}}
105 comments:
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
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.
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
Hello,
I have tested the code and runs great with 1 file, but when I transfer several small files (one after the other) I can only receive 2-3 files, the next file receptions are mistaken. I think it could be a syncronization problem. Do you have an idea about changes I have to do for transfer succesfully 5 small files in the same TCP connection through the Internet? Thanks in advance, and congratulations for your work and blog.
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
hi suman i am working on ur code it working fine on one pc but when i am trying to run on another computer it generate error
Actually i am working on program that download a file from web and save it another pc
i done downloading part but i am not able to do saving part
i am waiting for ur reply
and i read all comments but unable to do ipaddress part if u able to help me plz help me
hi suman i am working on ur code it working fine on one pc but when i am trying to run on another computer it generate error
Actually i am working on program that download a file from web and save it another pc
i done downloading part but i am not able to do saving part
i am waiting for ur reply
and i read all comments but unable to do ipaddress part if u able to help me plz help me
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 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 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........
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???
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
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
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
thank you Biswas i just kept a templet of the code .just go trough this.....
for (; ; )
{
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += " ";
}
}
i just used for loop....to repeat the same file.....i developed a code in java based on same concept it worked well for me...i don't know why i am getting errors in .net
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)
thnx for such a nice code ..cleared my concepts..thnx a lot suman
Rahul has commented as below:
I really like your blog and would suggest you to buy your own domain and hosting. You are a good blogger and you should take blogging seriously :)
Hi Rahul,
Thanks for you great reply. I will try to do it in future. As you have posted some links so I am deleting your Reply. Sorry, I do not provide any back link in my blog.
Regards
Suman
i'm brinda . working as software developer. i saw in ur project simple file transfer in between 2 computer. i'm developing LAN Communicaitor. i want to transfer files to another one computer over the networking . but i have only one application.that application installed in 2 computer or more than one computer . now i want to send files to anyone computer over the installed that application. in my project no server and no client. that application act as sender and receiver .
could plz help me this situation.... i'm in critical situation for my problem...
Hi Brinda,
As it is in LAN so any computer may become Client and/or Server. In fact Server is require only for Internet based solution because generally users do not use any static dedicated IP and for that from outside LAN client computer cant access directly. So as a middle person (you may think) need server. With Server situation comes like 2 person's conversation with two different languages by taking help of a middle man (server). It is like 1st person: Spanish, 2nd person: Hindi then 3rd person must know Spanish and Hindi. In real 1st will tell to 3rd and then 3rd will convert and tell to 2nd.
But for LAN 1st and 2nd can talk directly, because they know their IPs (like same language).
Tech solution:
So you need to implement Server and Client code in a single application. It will be two different classes. In your application/computer you need two objects for these two classes. So for two clients there will be total 4 objects and for 3 clients 6 object. These will work exactly like when you test your code in a single computer (then sever and client exists in a single machine).
You need to register clients that mean each computer will know IP of other computer and when try to send data can create socket object by using these IP and can send data using this socket object.
I believe you can now understood the solution how may apply. To implement this you need to know basic thing about socket programming and I have provided these information in my blog. So for code reference you may go though my blog post one by one. Start from oldest to latest.
Thanks for asking questions,
Suman
thanks for ur replied :)
could plz give me example code for that :(
Hi Brinda
I dont have any ready code for you. If you want can write own code by using my 2GB file transfer code, it will not a difficult task.
Suman
Hi Brinda
I dont have any ready code for you. If you want can write own code by using my 2GB file transfer code, it will not a difficult task.
Suman
Hi Brinda
I dont have any ready code for you. If you want can write own code by using my 2GB file transfer code, it will not a difficult task.
Suman
Hi Suman,
I tried to use your code into my app, but I stumble upon 2 issues:
1. If I use the server to send files greater than 8KB, the client doesn't receive the whole file (I'm using it to send&receive XML files)
2. If I need to receive files from a certain client (that uses another code than you've designed), how can I still receive the file? (i mean that you've put name of the file after empty 4 bytes, then the file content)
First issue is more important for the moment(so I can use your solution as client-server for now)
Than you in advance!
Adi
Hi Adi,
This particular code has written for small file transfer so it can not send large file from Server to Client.
This code is similar of “FILE TRANSFER USING C# .NET SOCKET PROGRAMMING” (URL:
http://socketprogramming.blogspot.in/2007/11/file-transfer-using-c-socket.html) but written just for opposite side data transfer. To send large file from Client to Server has mentioned at “LARGE FILE (2 GB) TRANSFER USING C# SOCKET” (URL:
http://socketprogramming.blogspot.in/2009/02/transfer-large-file-2gb-using-socket-in.html). This large one has been written based on small file transfer so if you understood these two posts clearly then small file transfer from Server to Client you can modify to send large file and I have left this one for my blog readers as a home work! Read these two and try to understand then you can write require code your self. For better I would recommend read all posts one by one so can understood more clearly.
One more thing, if my blog helps you then don’t forget to make some click on side ads ;-).
Regards,
Suman
Hey Suman, I actually wanted to know whether how will i be able to analyse the bandwidth usage of each computer using C#.
good blog :) I also write articles about .NET developing
Hi Suman,
its been 2 year since you develope this aplication and i have been read it today
i tested it, and its says "file sending failed, an address is in compatible with the request protocol was used ::1:5656
is there any way to change its ip address?
could you give me some example on that
i dont know if this message read or not, anyway thanks
Hi Fikri,
Thanks for comments. ::1:65... actual things are :. ::1 is similar to 127.0.0.1 that is local host and next is port number.
Server and client is running in same machine. For your project use same port number in server and client.
Thanks
Suman
Can I use your code. to put the file without runf over clint side?
That I'm needing is to send the file from the server to the client. ?m assuming that both are on the same network. if yes. on which statmente i can specifify the source from theser and the target for the client.
Can I use your code. to put the file without runf over clint side?
That I'm needing is to send the file from the server to the client. ?m assuming that both are on the same network. if yes. on which statmente i can specifify the source from theser and the target for the client.
How can use your code to push a file from the server to the client. I'm assuming both are on same network
Yes you can use my code for your work.
Hi Suman
I send a 8 KB .txt file in which 79 lines from server side. But I received only 1KB in which only 6 lines from client side. Please advice me how to solve it. Thanks for this tutorial which is very useful to me.
Reply·Email·View Thread·Permalink·Bookmark | Edit·Delete
Post a Comment