File transfer using C# socket is Client-Server combined process and quite complex too. This process we can divide in three phases.
- Preparation stage for Server and Client.
- Establish communication channel to send-receive data between Client and Server.
- Break the communication channel and release all resources.
To complete data transfer from client to server need to follow below steps as describe in table. Later discussing about each steps but before that go trough the logic which I am going to follow.
Phase 1, Preparation: In that phase server and client both prepared to send some data.
File Transfer from
Client to Server
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.
5. 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. Start preparations
to store incoming byte data from client.
8. Server receives file byte data along with file name
and stores it in byte array.
9. Server retrieve file name from byte data.
10. Server opens a binary stream writer with file name
to store byte data in it.
11. Once file save complete server closes binary stream
writer and server socket objects.
14 Server program ends here.
|
2. Client creates an IP End Point and a socket object.
3. Prepare byte data from file
which will be sent to server.
4. Try to connect to
server using client socket by help of IP end point.
7. Client starts sending
byte data over connected socket.
12. Once data transfer
complete and server closes socket connection, client also close client socket
object.
13. Client program work ends
here.
|
Phase 1, Preparation: In that phase server and client both prepared to send some data.
At Server: Server makes an object of IPEndPoint class with some Port number with some IP address. Then creates a socket object with Internetwork family with protocol type IP(or IDP or else) to transfer Stream type data. At last bind this socket objects with that IPEndPoint object and place socket in listen mode to accept client request.
At Client: Client makes another IPEndPoint object with Server IP address and same port number. Then creates a socket object as same as Server socket object in same way. After completing these client reads a file and stores bytes data in a byte array object.
Phase 2, Establish communication and transfer data: Now client socket tries to connect to server socket which was in listen mode. When server socket get requests from client then it accept request and established connection between server and client by producing a new socket object. Next data transmission operation continues by that new socket object.
When new client socket request accepted by server and connection established then client send byte data by “socket-object. Send()” method to server and at server end these data received by “socket-object. Receive()” method. When data successfully received at server end, server saves these bytes in a file using byte data stream.
For large file, “these data read at client -send to server-receive at server end - save received data at server end” these steps are perform repeatedly until client reach at EOF (End Of File). But in this program only small file covered for this no need of looping, for this type of example read my “Send 2GB file using TCP socket programming” article.
Phase 3, Break communication
channel and release resources: When last
slice of byte data saved at server, client and server close the socket object
and release all resource like file stream, socket object etc.
By that way a file
transferred from client to server. But there has no way to call a client from
server and send file. My example describe how to send file from client to
server but can you imagine how opposite done? Yes if you able learn client to
server data transfer properly then it is very easy. Try your self first, if
failed then try it again and continue at least three times, then you will able
to do it. But….but again failed then ask me I will help you about it :-).
For code url is:
Client Code:
[C#]
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 PROGRAMMING - 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);string fileName = "Your File Name";string filePath = "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.Connect(ipEnd);clientSock.Send(clientData);Console.WriteLine("File:{0} has been sent.", fileName);clientSock.Close();Console.ReadLine();}catch (Exception ex){Console.WriteLine("File Sending fail." + ex.Message);}}}
}[Visual Basic]
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Namespace Client_Socket
'FILE TRANSFER USING C#.NET SOCKET PROGRAMMING- CLIENT
Class Program
Private Shared Sub Main(ByVal args As String())
Try
Console.WriteLine("That program can transfer small file. I've test up to 850kb file")
Dim ipAddress As IPAddress() = Dns.GetHostAddresses("localhost")
Dim ipEnd As New IPEndPoint(ipAddress(0), 5656)
Dim clientSock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)
Dim fileName As String = "Your File Name"
Dim filePath As String = "Your File Path"
Dim fileNameByte As Byte() = Encoding.ASCII.GetBytes(fileName)
Dim fileData As Byte() = File.ReadAllBytes(filePath + fileName)
Dim clientData As Byte() = New Byte(4 + fileNameByte.Length + (fileData.Length - 1)) {}
Dim fileNameLen As Byte() = BitConverter.GetBytes(fileNameByte.Length)
fileNameLen.CopyTo(clientData, 0)
fileNameByte.CopyTo(clientData, 4)
fileData.CopyTo(clientData, 4 + fileNameByte.Length)
clientSock.Connect(ipEnd)
clientSock.Send(clientData)
Console.WriteLine("File:{0} has been sent.", fileName)
clientSock.Close()
Console.ReadLine()
Catch ex As Exception
Console.WriteLine("File Sending fail." & ex.Message)
End Try
End Sub
End Class
End Namespace
Continued code...
Server Code:
[C#]
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 PROGRAMMING - 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);Socket clientSock = sock.Accept();byte[] clientData = new byte[1024 * 5000];string receivedPath = "e:/";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 Receiving fail." + ex.Message);}}}}
[Visual Basic]
Imports SystemImports System.Collections.GenericImports System.TextImports System.NetImports System.Net.SocketsImports System.IONamespace beginSocketServer'FILE TRANSFER USING C#.NET SOCKET PROGRAMMING- SERVERClass ProgramPrivate Shared Sub Main(ByVal args As String())TryConsole.WriteLine("That program can transfer small file. I've test up to 850kb file")Dim ipEnd As New IPEndPoint(IPAddress.Any, 5656)Dim sock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)sock.Bind(ipEnd)sock.Listen(100)Dim clientSock As Socket = sock.Accept()Dim clientData As Byte() = New Byte(1024 5000 - 1) {}Dim receivedPath As String = "e:/"Dim receivedBytesLen As Integer = clientSock.Receive(clientData)Dim fileNameLen As Integer = BitConverter.ToInt32(clientData, 0)Dim fileName As String = Encoding.ASCII.GetString(clientData, 4, fileNameLen)Console.WriteLine("Client:{0} connected & File {1} started received.", clientSock.RemoteEndPoint, fileName)Dim bWrite As 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 ex As ExceptionConsole.WriteLine("File Receiving fail." & ex.Message)End TryEnd SubEnd ClassEnd Namespace