Server
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class 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("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);
}
}
}
}
Output:
Server Started...
Client Connected...
hai
Client: hello