Please check this
Server
private static TcpListener ser;
private static Socket sock;
static void Main(string[] args)
{
try
{
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
ser = new TcpListener(localAddr, 4545);
ser.Start();
Console.WriteLine("Client Connected.........");
Console.WriteLine("Server Started...");
sock = ser.AcceptSocket();
Console.WriteLine("Client Connected...");
Thread t = new Thread(new ThreadStart(ReadClientData));
t.Start();
while (sock.Connected)
{
string data = Console.ReadLine();
byte[] bytedata = Encoding.ASCII.GetBytes(data);
sock.Send(bytedata, bytedata.Length, 0);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
private static void ReadClientData()
{
while (sock.Connected)
{
try
{
byte[] Buffer = new byte[255];
sock.Receive(Buffer, 255, 0);
string data = Encoding.ASCII.GetString(Buffer);
Console.WriteLine("Client: " + data);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Client
private static TcpClient client = new TcpClient();
private static NetworkStream ns;
static void Main(string[] args)
{
try
{
client.Connect("localhost",4545);
Console.WriteLine("Connected with server .....");
ns = client.GetStream();
Thread t = new Thread(new ThreadStart(ReadServerData));
t.Start();
while (client.Connected)
{
string data = Console.ReadLine();
byte[] bytedata = Encoding.ASCII.GetBytes(data);
ns.Write(bytedata, 0, bytedata.Length);
}
}
catch(Exception ex)
{
Console.Write(ex.Message);
Console.ReadLine();
}
}
private static void ReadServerData()
{
while(client.Connected)
{
try
{
byte[] Buffer = new byte[255];
ns.Read(Buffer,0,255);
string data = Encoding.ASCII.GetString(Buffer);
Console.WriteLine("Server: " +data);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
This is a simple console application which send and receive plain text.