I obtained the following code from MSDN :
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MyTcpListener
{
public static void Main()
{
TcpListener server = null;
try
{
Int32 port = 13000; // Set the TcpListener on port 13000.
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port); // TcpListener server = new TcpListener(port);
server.Start(); // Start listening for client requests.
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();// Get a stream object for reading and writing
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) // Loop to receive all the data sent by the client.
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); // Translate data bytes to a ASCII string.
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();// Process the data sent by the client.
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length); // Send back a response.
Console.WriteLine("Sent: {0}", data);
if(data == "STOP")
{
Console.WriteLine("Stop command Received.");
Console.ReadKey();
Environment.Exit(0);
}
Console.WriteLine(data.Length);
}
client.Close(); // Shutdown and end connection
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();// Stop listening for new clients.
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
except the following lines which were inserted by me:
if(data == "STOP")
{
Console.WriteLine("Stop command Received.");
Console.ReadKey();
Environment.Exit(0);
}
I sent a string "STOP" via a tcp client. However, in the server, comparing the received string "STOP" against "STOP" in the 'if block' was of no use ie., nothing in that block got executed.
What is the actual error in this approach ? What changes should I make to compare the strings properly ?