Introduction & Background
When I tried to learn socket application in .NET (C#), I did not find any good ready made socket code to learn it. I had a problem and for that, I built a blog especially for socket application. Here I give just one application, but in my blog I have a few code examples to learn socket in C#.NET. You can find long and practical C# code on my blog at www.socketprogramming.blogspot.com.
I've written code to transfer a file from client to server using C#.NET socket application. That code has used TCP protocol to send file, that can run in LAN and WAN (Internet). It can send a small file from client to server, I've tested it with 1.5MB. But anyone can modify that code and can build an application to send a large file with multiple client support by a single server.
I'm giving an overview/steps to make a socket application. Here, there are two applications; one is Server and another is Client. At first, the server will open a port and will wait for a request from the client, and the client will try to connect to the server. After getting a connection request, the server will accept it and will make a successful connection. After a successful connection, the client will send data in byte array and the server will catch and hold it. Then, it will save these bytes. After successful data transfer, the server will save data and disconnect client.
I think after reading this code, one can understand how a socket application works. If anyone is unable to understand, then I request them to read my blog. If you still have any questions, please contact me via blog comment/mail and I will answer.
Using the Code
The complete server and client code is here in zip format. You can just download it and use it. I'm giving two code blocks of Server and Client.
The core code for Server application with some comments is as given below:
class FTServerCode
{
IPEndPoint ipEnd;
Socket sock;
public FTServerCode()
{
ipEnd = new IPEndPoint(IPAddress.Any, 5656);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
public static string receivedPath;
public static string curMsg = "Stopped";
public void StartServer()
{
try
{
curMsg = "Starting...";
sock.Listen(100);
byte[] clientData = new byte[1024 * 5000];
int receivedBytesLen = clientSock.Receive(clientData);
curMsg = "Receiving data...";
int fileNameLen = BitConverter.ToInt32(clientData, 0);
BinaryWriter bWrite = new BinaryWriter(File.Open
(receivedPath +"/"+ fileName, FileMode.Append)); ;
curMsg = "Saving file...";
bWrite.Close();
clientSock.Close();
curMsg = "Received & Saved file; Server Stopped.";
}
catch (Exception ex)
{
curMsg = "File Receiving error.";
}
}
}
The code for client application is as follows:
class FTClientCode
{
public static string curMsg = "Idle";
public static void SendFile(string fileName)
{
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
string filePath = "";
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
if (fileNameByte.Length > 850 * 1024)
{
curMsg = "File size is more than 850kb, please try with small file.";
return;
}
curMsg = "Buffering ...";
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);
curMsg = "Connection to server ...";
clientSock.Connect(ipEnd);
curMsg = "Disconnecting...";
clientSock.Close();
curMsg = "File transferred.";
}
catch (Exception ex)
{
if(ex.Message=="No connection could be made because the target machine
actively refused it")
curMsg="File Sending fail. Because server not running." ;
else
curMsg = "File Sending fail." + ex.Message;
}
}
}
I hope you understand how a file can be sent from client to server via TCP socket in C#. Here I've write simple code to send a single file, but it’s the basic code. By modifying that code, multiple files can be sent from client to server, and by incorporating thread technology, that server can handle multiple clients at a time. And by using both end binary writer & reader can send large files too. Here, we will give a small problem for TCP buffer overflow that needs to send data after slicing. To know more on Socket programming, please visit my blog at http://socketprogramming.blogspot.com/.