Sockets programming in C# is the way of connecting two nodes with each other over a network so that they can communicate easily without losing any data. One socket (node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server.
Client Server Socket Programming in C# |
Here this blog shares code examples in C# to develop socket client and socket server in c#. Here both the client server programming will use TCP port to connect each other.
In C# socket programming can be developed using Socket class which comes under the System.Net.Sockets and System.Net.Sockets.dll assembly. Before starting to discuss the code examples let understand about the Socket class.
Socket ClassThe Socket class provides a rich set of methods and properties for network communications. The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration.
The Socket class follows the .NET Framework naming pattern for asynchronous methods. For example, the synchronous Receive method corresponds to the asynchronous ReceiveAsync variants.
Socket ServerHere the below code is to develop socket server in C#.
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
socket.Bind(new IPEndPoint(System.Net.IPAddress.Parse("192.168.0.137"), 8080));
int buffersize = 8 * 1024;
AsyncCallback recv = null;
EndPoint remoteEndPoint = new IPEndPoint(System.Net.IPAddress.Any, 8080);
while (true)
{
try
{
using (State state = new State())
{
socket.BeginReceiveFrom(state.buffer, 0, buffersize, SocketFlags.None, ref remoteEndPoint, recv = (ar) =>
{
State st = (State)ar.AsyncState;
int bytes = socket.EndReceiveFrom(ar, ref remoteEndPoint);
socket.BeginReceiveFrom(state.buffer, 0, buffersize, SocketFlags.None, ref remoteEndPoint, recv, st);
string receiveddata = Encoding.ASCII.GetString(st.buffer, 0, bytes);
Console.WriteLine("Received {0}: {1},{2}", System.DateTime.Now.ToLongTimeString(), remoteEndPoint.ToString(), receiveddata);
//Send data back to client
byte[] datatosent = Encoding.ASCII.GetBytes("Received Data");
socket.BeginSendTo(datatosent, 0, datatosent.Length, SocketFlags.None, remoteEndPoint, recv = (ar1) =>
{
State st1 = (State)ar.AsyncState;
int bytes1 = socket.EndSendTo(ar1);
Console.WriteLine("SEND {0}: {1}, {2}", System.DateTime.Now.ToLongTimeString(), remoteEndPoint.ToString(), data);
}, state);
}, state);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Source {0}, Message {1}", ex.Source.ToString(), ex.Message);
}
}
Socket Client
Here the below code is to develop socket client in C#.
UdpClient client = new UdpClient(8080);
IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse("192.168.0.137"), 8080);
client.Connect(endPoint);
while (true)
{
Console.WriteLine("Routin Started");
IPEndPoint remoteEndPoint = new IPEndPoint(System.Net.IPAddress.Any, 8080);
var data = client.Receive(ref remoteEndPoint);
Console.WriteLine("Receveide Data : " + data.ToString());
Console.WriteLine("Receveide From : " + remoteEndPoint.ToString());
string sentdata = DateTime.Now.Ticks.ToString();
Byte[] sendBytes = Encoding.ASCII.GetBytes(sentdata);
Console.WriteLine("Sent Data : " + sentdata);
client.Send(sendBytes, sendBytes.Length);
if (data == null)
Console.WriteLine("No data received");
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Routin Ended");
}
State Class
public class State : IDisposable
{
public byte[] buffer;
public State()
{
try
{
buffer = new byte[8 * 1024];
}
catch (Exception ex)
{
}
}
public void Dispose()
{
//if (this.buffer != null)
// this.buffer = null;
}
}
Thanks