Server side code:
static void Main(string[] args)
{
static Socket sck;
Console.WriteLine("Server Started...");
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(0, 1234));
while (true)
{
sck.Listen(100);
Socket accepted = sck.Accept();
buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
formatted[i] = buffer[i];
string strdata = Encoding.ASCII.GetString(formatted);
Console.WriteLine(strdata + "\r");
// sck.Close();
}
Client side code:
static void Main(string[] args)
{
static Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
try
{
sck.Connect(localEndpt);
}
catch
{
Console.Write("Unable to Connect");
}
while (true)
{
Console.WriteLine("Enter Text");
string sendtext = Console.ReadLine();
byte[] Data = Encoding.ASCII.GetBytes(sendtext);
sck.Send(Data);
Console.WriteLine("Data Sent!");
//sck.Close();
//Console.Read();
}
I want to send text from the Client side multiple times, however the text is sent only the first time. Please tell me where am i going wrong.
The problem is on your server. You are in a loop listening for a new connection, accepting it and receiving data. Yet what happens is the listening statement see’s a client who wants to connect. Your accept statement actually connects the client and your receive statement receieves the first data. After that your server starts listening for a new connection again but is not receiving more data from the already existing connection. You should build a loop around the Accept statement and a loop around the Receive statement on your server to fix this problem