Socket Programming in C# .Net

Dot Net Programming in C# with source code and DLL file. Covers Socket, Remoting, Stored Procedure, ASP.Net, IO, Web Service, Windows Service, Installer, Console Programming, Win Forms, Web Forms, Ajax, Web publishing, Text Chat, Large File Transfer, File Handling etc.

Download source code from here

File Transfer using C# Socket

File transfer using C# socket is Client-Server combined process and quite complex too. This process we can divide in three phases.

  1. Preparation stage for Server and Client.
  2. Establish communication channel to send-receive data between Client and Server.
  3. Break the communication channel and release all resources.

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” 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 Client code url is:

http://rapidshare.com/files/269517016/FT_Client_Console.zip

For Server code url is:

http://rapidshare.com/files/269517017/FT_Server_Console.zip



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 - 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);


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 - 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


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 - 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);
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 System
Imports System.Collections.Generic
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Namespace beginSocketServer
'FILE TRANSFER USING C#.NET SOCKET - SERVER
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 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 Exception
Console.WriteLine("File Receiving fail." & ex.Message)
End Try
End Sub
End Class
End Namespace

Labels: , , , , ,

File Transfer using C# Socket

File transfer using C# socket is Client-Server combined process and quite complex too. This process we can divide in three phases.

  1. Preparation stage for Server and Client.
  2. Establish communication channel to send-receive data between Client and Server.
  3. Break the communication channel and release all resources.

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” 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 Client code url is:

http://rapidshare.com/files/269517016/FT_Client_Console.zip

For Server code url is:

http://rapidshare.com/files/269517017/FT_Server_Console.zip



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 - 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);


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 - 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


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 - 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);
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 System
Imports System.Collections.Generic
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Namespace beginSocketServer
'FILE TRANSFER USING C#.NET SOCKET - SERVER
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 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 Exception
Console.WriteLine("File Receiving fail." & ex.Message)
End Try
End Sub
End Class
End Namespace

Labels: , , , , ,

  1. Blogger vaibhav | November 26, 2007 6:21 PM |  

    nice 1

  2. Blogger Michael | May 23, 2008 8:07 AM |  

    Thank you for this.

  3. Blogger Pratiksha | May 26, 2008 4:26 AM |  

    How to transfer large files....5 mb or more


    Thanks
    Pratiksha

  4. Blogger ေသာ ၾကာ သူ ရ | June 11, 2008 1:50 AM |  

    Nice code, there is one thing i want to know, How can i send response message and files from server to client and how can client receive them?
    Thant
    proteus

  5. Blogger SHINOJ | June 25, 2008 3:15 AM |  

    how to send emotions through sockets as bytes?and convert to image plz send reply

  6. Blogger Chua | July 13, 2008 9:00 PM |  

    Thanks for answering my emailed queries earlier.

    However, I have another problem. I converted your client over to .NET Compact Framework compatable, because I'm trying it through a Windows Mobile 6.
    I just changed your

    byte[] fileData = File.ReadAllBytes(filePath + fileName);

    to

    public static byte[] ReadAllBytes(string path){ byte[] buffer; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { int offset = 0; int count = (int)fs.Length; buffer = new byte[count]; while (count > 0) { int bytesRead = fs.Read(buffer, offset, count); offset += bytesRead; count -= bytesRead; } } return buffer;}

    because .NET Compact Framework doesn't support File.ReadAllBytes I guess. It should work the same.

    However, my problem here is that it feels as if there is only 1 transmission. The actual file size is 74.3KB only, but the 1st few parts were allowed to be sent over.

    Do you have any recommendations for this? Sorry, would also like to ask whether only 1 time transmission is catered for it only?

    Thank you!

  7. Blogger akki | July 17, 2008 11:44 PM |  

    Its is seriously a simple and tidy code....but as i am new in socket programming i am not able to transfer files of large size....so, could u plz let me know how to transfer file of around 25MB size? Thanks in advance :)

    Cheers,
    Prashant

  8. Blogger Pat | August 14, 2008 1:37 AM |  

    Hi,
    Thanks for these great examples. I am tring to create Asynchronous File Transfer Client / Server applications. Using the MS code I can get the Asynchronous examples working however now I'm tring to modify this code to send files instead of strings. It seems examples of this are hard to come by on the web. Do you have any code examples that might help me? Thank you.

  9. Blogger ashish | November 1, 2008 4:38 AM |  

    I am having exception as
    "Socket closed du to Dead Network"
    want help

  10. Blogger Ege Ilıcak | February 18, 2009 10:36 AM |  

    thank you for the example. But I want to know that how can we transfer large files? Can you give an example?

    Thanks. Ege.

  11. Blogger Mariam | February 25, 2009 7:25 PM |  

    Hey I am new to this ,can u plz tell me how to send videos from one computer to another (sending the videos frame by frame)

  12. Blogger Mariam | February 25, 2009 7:28 PM |  

    hey i am new to this can u plz tell me which of the two(i.e. UDP and TCP)to use when i want to tranfers videos frame by frame from one computer to another and also how do i do it?

  13. Blogger Suman Biswas | February 25, 2009 11:30 PM |  

    Hi Mariam,
    You can use UDP to transfer video data, also for voice UDP is applicable.

    Thanks
    Suman

  14. Blogger John Blesswin | March 10, 2009 1:35 AM |  

    thanks for this da..
    its nice

    but i want to transfer large files.

  15. Blogger Mariam | March 11, 2009 5:26 AM |  

    thanks suman,
    but i need guidance as to how am i supposed to go about it i m totally clue less.
    Can any of u guyz plz guide me as to how i should proceed?

  16. Blogger Ege Ilıcak | April 3, 2009 6:22 AM |  

    Here is an example of how to transfer large files:

    Client Side:
    http://codetechnic.blogspot.com/2009/02/sending-large-files-over-tcpip.html

    Server Side:
    http://codetechnic.blogspot.com/2009/02/receiving-large-files-over-tcpip-in-c.html

  17. Blogger John Blesswin | April 3, 2009 7:22 AM |  

    Thank u 4 this program .i try it . it work nice fully..

    and one more program i need socket program send audio files in java language..

    plz send its urgent ...
    tc
    bye

  18. Blogger Suman Biswas | April 3, 2009 7:26 AM |  

    Sorry I don't write code in Java.

    Suman

  19. Blogger Aljaz | October 14, 2009 2:24 PM |  

    Hi! I have made file transfer from client to server map to work. Now i don't know how to make it opposite, to transfer from server to client. If anyone could help me, plz let me know. My email is: aljazstraser@gmail.com

  20. Blogger geet | November 10, 2009 8:56 PM |  

    i run this project it runs successfully but when i enter file name and path in client application and press enter then it is showing me error "No connection could be made because the target machine actively refused it"

    Can any1 help me?

  21. Blogger Suman Biswas | November 10, 2009 11:38 PM |  

    Hi Geet,
    Your Server is not running or your client's server address/port is not correct, so it can not connect to server. So you are getting this error.

    Suman

  22. Blogger geet | November 11, 2009 1:49 AM |  

    i am running this on my computer so my client and server is both my computer (localhost)
    then how can it be wrong?

  23. Blogger Suman Biswas | November 11, 2009 1:54 AM |  

    Hi Geet,
    First run your server application then start client application.
    When you are trying to run client then plz check is it connecting to 'localhost' / 127.0.0.1 and use same port for server and client. You must be sure about this otherwise you will get same problem.

    This message comes from system only when client unable to find server.

    Thanks,
    Suman

  24. Blogger geet | November 11, 2009 4:31 AM |  

    i am not changing anything in the program written above
    If that is right then error should not be generated.

  25. Blogger Suman Biswas | November 11, 2009 4:40 AM |  

    Hi Geet,
    This is working fine...I have tested once again.

    Please check about your testing procedure.

    Run Server then Client.

    By the way, in client have you change the source file name and path?

    Thanks,
    Suman

  26. Blogger Suman Biswas | November 11, 2009 4:41 AM |  

    These two lines in client...

    string fileName = "PNR .txt";
    string filePath = @"C:\";

  27. Blogger Suman Biswas | November 11, 2009 4:42 AM |  

    These two lines in client...

    string fileName = "PNR .txt";
    string filePath = @"C:\";

  28. Blogger geet | November 11, 2009 5:23 AM |  

    it works thannx SUMAN

leave a response

Socket Programming in C# .Net

Dot Net Programming in C# with source code and DLL file. Covers Socket, Remoting, Stored Procedure, ASP.Net, IO, Web Service, Windows Service, Installer, Console Programming, Win Forms, Web Forms, Ajax, Web publishing, Text Chat, Large File Transfer, File Handling etc.

Download source code from here

Synchronous Server Socket using Network Stream in C# .Net

Hi frends,I’m back again with two sample socket application. These two project also for beginner’s in C#.Net Socket world. One of these is Server socket application and another is Client socket application. Both application has used NetworkStream class to send and receive data between Client and Server. These two has written based on previous articles on Socket programming and these are very easy to learn. I hope any one can understood these very easyly. If you feel any problem then please reply me via comment I will response these.

Here Server socket with Network stream in C# has written and in different blog post contains the client application. Both two has written based on synchronous communication mode, but in future I will show you, how you can built asynchronous socket application by these synchronous socket. So lets starts code.


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace NetworkStreamSocketServer
{
class Program
{
static void Main(string[] args)
{
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];

//With other Socket server application difference only here.
//Create an Network stream object and wait for client's request
NetworkStream ns = new NetworkStream(clientSock);

//Wait for new connection and to receive data from client
int receivedBytesLen = ns.Read(clientData, 0, clientData.Length);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
ns.Flush();//Free Stream buffer
Console.WriteLine("Received Data {0}", clientDataInString);

string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData = Encoding.ASCII.GetBytes(clientStr);
//Now network stream object send some data to client
ns.Write(sendData, 0, sendData.Length);
//Release all resources
ns.Close();
clientSock.Close();
Console.ReadLine();
}
}
}

Labels: , , , , , , ,

Synchronous Server Socket using Network Stream in C# .Net

Hi frends,I’m back again with two sample socket application. These two project also for beginner’s in C#.Net Socket world. One of these is Server socket application and another is Client socket application. Both application has used NetworkStream class to send and receive data between Client and Server. These two has written based on previous articles on Socket programming and these are very easy to learn. I hope any one can understood these very easyly. If you feel any problem then please reply me via comment I will response these.

Here Server socket with Network stream in C# has written and in different blog post contains the client application. Both two has written based on synchronous communication mode, but in future I will show you, how you can built asynchronous socket application by these synchronous socket. So lets starts code.


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace NetworkStreamSocketServer
{
class Program
{
static void Main(string[] args)
{
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];

//With other Socket server application difference only here.
//Create an Network stream object and wait for client's request
NetworkStream ns = new NetworkStream(clientSock);

//Wait for new connection and to receive data from client
int receivedBytesLen = ns.Read(clientData, 0, clientData.Length);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
ns.Flush();//Free Stream buffer
Console.WriteLine("Received Data {0}", clientDataInString);

string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData = Encoding.ASCII.GetBytes(clientStr);
//Now network stream object send some data to client
ns.Write(sendData, 0, sendData.Length);
//Release all resources
ns.Close();
clientSock.Close();
Console.ReadLine();
}
}
}

Labels: , , , , , , ,

  1. Blogger SHINOJ | June 4, 2008 9:23 AM |  

    How to send files client to client through server?

  2. Blogger Ravi | April 3, 2009 1:21 AM |  

    hi,

    i have developed Async Server using socket class. but it giving me 15 TPS. do u have any idea for high performance server.

    mcamail2002@gmail.com

  3. Blogger Suman Biswas | April 3, 2009 4:43 AM |  

    Hi Ravi,
    I can't understand about 15TPS (TPS?). So please enplane quite more clearly.


    Thanks,
    Suman

  4. Blogger Ravi | April 4, 2009 7:26 AM |  

    thanks for reply.Acually i,m talking about Txn Per Second (TPS). my server giving 15 TPS but want more than 15 TPS. that's why i am looking high perfomance Socket server or Multi threaded server.

    Thanks
    Ravi

leave a response

Socket Programming in C# .Net

Dot Net Programming in C# with source code and DLL file. Covers Socket, Remoting, Stored Procedure, ASP.Net, IO, Web Service, Windows Service, Installer, Console Programming, Win Forms, Web Forms, Ajax, Web publishing, Text Chat, Large File Transfer, File Handling etc.

Download source code from here

Synchronous Server Socket using Network Stream in C# .Net

Hi frends,I’m back again with two sample socket application. These two project also for beginner’s in C#.Net Socket world. One of these is Server socket application and another is Client socket application. Both application has used NetworkStream class to send and receive data between Client and Server. These two has written based on previous articles on Socket programming and these are very easy to learn. I hope any one can understood these very easyly. If you feel any problem then please reply me via comment I will response these.

Here Server socket with Network stream in C# has written and in different blog post contains the client application. Both two has written based on synchronous communication mode, but in future I will show you, how you can built asynchronous socket application by these synchronous socket. So lets starts code.


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace NetworkStreamSocketServer
{
class Program
{
static void Main(string[] args)
{
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];

//With other Socket server application difference only here.
//Create an Network stream object and wait for client's request
NetworkStream ns = new NetworkStream(clientSock);

//Wait for new connection and to receive data from client
int receivedBytesLen = ns.Read(clientData, 0, clientData.Length);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
ns.Flush();//Free Stream buffer
Console.WriteLine("Received Data {0}", clientDataInString);

string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData = Encoding.ASCII.GetBytes(clientStr);
//Now network stream object send some data to client
ns.Write(sendData, 0, sendData.Length);
//Release all resources
ns.Close();
clientSock.Close();
Console.ReadLine();
}
}
}

Labels: , , , , , , ,

Synchronous Server Socket using Network Stream in C# .Net

Hi frends,I’m back again with two sample socket application. These two project also for beginner’s in C#.Net Socket world. One of these is Server socket application and another is Client socket application. Both application has used NetworkStream class to send and receive data between Client and Server. These two has written based on previous articles on Socket programming and these are very easy to learn. I hope any one can understood these very easyly. If you feel any problem then please reply me via comment I will response these.

Here Server socket with Network stream in C# has written and in different blog post contains the client application. Both two has written based on synchronous communication mode, but in future I will show you, how you can built asynchronous socket application by these synchronous socket. So lets starts code.


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace NetworkStreamSocketServer
{
class Program
{
static void Main(string[] args)
{
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];

//With other Socket server application difference only here.
//Create an Network stream object and wait for client's request
NetworkStream ns = new NetworkStream(clientSock);

//Wait for new connection and to receive data from client
int receivedBytesLen = ns.Read(clientData, 0, clientData.Length);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
ns.Flush();//Free Stream buffer
Console.WriteLine("Received Data {0}", clientDataInString);

string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData = Encoding.ASCII.GetBytes(clientStr);
//Now network stream object send some data to client
ns.Write(sendData, 0, sendData.Length);
//Release all resources
ns.Close();
clientSock.Close();
Console.ReadLine();
}
}
}

Labels: , , , , , , ,

  1. Blogger SIDHU | September 15, 2008 3:30 PM |  

    Hi

    my application is sengind messages to a TCP port and i want to access those messages for testing. how can i do that

leave a response

Socket Programming in C# .Net

Dot Net Programming in C# with source code and DLL file. Covers Socket, Remoting, Stored Procedure, ASP.Net, IO, Web Service, Windows Service, Installer, Console Programming, Win Forms, Web Forms, Ajax, Web publishing, Text Chat, Large File Transfer, File Handling etc.

Download source code from here

Synchronous Client Socket using Network Stream in C# .Net

Hi frends,I’m back again with two sample socket application. These two project also for beginner’s in C#.Net Socket world. One of these is Server socket application and another is Client socket application. Both application has used NetworkStream class to send and receive data between Client and Server. These two has written based on previous articles on Socket programming and these are very easy to learn. I hope any one can understood these very easyly. If you feel any problem then please reply me via comment I will response these.

Here Client socket with Network stream in C# .Net has written and in different blog post contains the Server application. Both two has written based on synchronous communication mode, but in future I will show you, how you can built asynchronous socket application by these synchronous socket. So lets starts code.


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace NetworkStreamSocketClient
{
class Program
{
static void Main(string[] args)
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
clientSocket.Connect(ipEnd);

string strData = "Message from client end.";
byte[] clientData = new byte[1024];
clientData = Encoding.ASCII.GetBytes(strData);

//Difference is here only, use of Network Stream class.
//Just create a object of Network Stream class with your estublished socket, then use it.
NetworkStream ns = new NetworkStream(clientSocket);

//Write function writes all bytes to send receiver end of connected socket.
ns.Write(clientData, 0, clientData.Length);

//Flush() use to clear all data from Stream object to future use.
ns.Flush();

byte[] serverData = new byte[1024];
//Now stream object wait for receive response from other end.
int length = ns.Read(serverData, 0, serverData.Length);
Console.WriteLine(Encoding.ASCII.GetString(serverData, 0, length));
//Communication completed, now free all resource
ns.Close();
clientSocket.Close();
Console.ReadLine();
}
}
}


Labels: , , , , ,

Synchronous Client Socket using Network Stream in C# .Net

Hi frends,I’m back again with two sample socket application. These two project also for beginner’s in C#.Net Socket world. One of these is Server socket application and another is Client socket application. Both application has used NetworkStream class to send and receive data between Client and Server. These two has written based on previous articles on Socket programming and these are very easy to learn. I hope any one can understood these very easyly. If you feel any problem then please reply me via comment I will response these.

Here Client socket with Network stream in C# .Net has written and in different blog post contains the Server application. Both two has written based on synchronous communication mode, but in future I will show you, how you can built asynchronous socket application by these synchronous socket. So lets starts code.


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace NetworkStreamSocketClient
{
class Program
{
static void Main(string[] args)
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
clientSocket.Connect(ipEnd);

string strData = "Message from client end.";
byte[] clientData = new byte[1024];
clientData = Encoding.ASCII.GetBytes(strData);

//Difference is here only, use of Network Stream class.
//Just create a object of Network Stream class with your estublished socket, then use it.
NetworkStream ns = new NetworkStream(clientSocket);

//Write function writes all bytes to send receiver end of connected socket.
ns.Write(clientData, 0, clientData.Length);

//Flush() use to clear all data from Stream object to future use.
ns.Flush();

byte[] serverData = new byte[1024];
//Now stream object wait for receive response from other end.
int length = ns.Read(serverData, 0, serverData.Length);
Console.WriteLine(Encoding.ASCII.GetString(serverData, 0, length));
//Communication completed, now free all resource
ns.Close();
clientSocket.Close();
Console.ReadLine();
}
}
}


Labels: , , , , ,

  1. Blogger Huu Nhan | July 15, 2008 2:38 AM |  

    I have problem, i write program send file : clientA -file-> server -file-> clientB. I send file from clientA to server successfull, but i can't send file from server -> clientB, with error "non-socket"....
    I think, server unknown port on clientB, althrough I save client connection information in array.

  2. Blogger Chua | September 5, 2008 12:32 PM |  

    I would like to ask, you said you used synchronous sockets for asynchronous transfer. How to use these synchronous sockets for synchronous transfer? Thank you!

leave a response