I create a simple application in socket programming. I think this is simple way to achieved that. so that is why I am sharing this. In this program you can create server program and client program. And you can also send and received message from client and server. here is my code
Server Program :-
class Program
{
private const int port = 4532;
static void Main(string[] args)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 4532);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for client");
Socket client = socket.Accept();
IPEndPoint clientIP = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine(" >> Connected with" + clientIP.Address + "at port" + clientIP.Port);
Console.WriteLine(" >> Accept connection from client");
string welcome = "Welcome";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
Console.WriteLine("......");
Console.Read();
}
}
Client Program :-
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4532);
Console.WriteLine("Client Started");
try
{
socket.Connect(ip);
}
catch(SocketException e)
{
Console.WriteLine("Enable to connect");
}
Console.WriteLine("Conneted to server");
byte[] data = new byte[1024];
int receivedata = socket.Receive(data);
string stringdata = Encoding.ASCII.GetString(data, 0, receivedata);
Console.WriteLine(stringdata);
Console.Read();
}
}
Well, it is not entirely right.
Note that Encoding.ASCII.GetBytes
will give you a new array each time, so that new byte[1024]
initialization is worthless, the array maybe bigger if the string is bigger.
What happen if the server sends a payload more than 1024? The client will truncate the message, that will cause serialization errors if you are using a structured data format like XML or JSON. In TCP communications you need to define a protocol to frame data, in a way that your code can determine when a message has started or ended, for example a message per line or something more sophisticated like the WebSocket framing.
Note that the server will accept just one client, send a welcome and get stuck in Console.Read
. It should listen for more clients in a loop, and start a new thread per connected client or use asynchronous operations. Same for the client ,it should listen for messages in a loop.
Consider async/await for expanding your example further. A production ready TCP server needs to be multithreading to scale appropriately.
Take a look at this example of asynchronous TCP server and client, not production ready, but enough for a proof of concept with buffer reading and asynchronous operations.