Monday, December 21, 2009

How to listen to TCP socket in C#

The code below illustrate how to listen to Tcp/Ip port for incoming stream.  The code can use to listen any port but some times you may encountered an exception (Refer).  

private void Run_Server()
{
// Listen to our own port 80 (HTTP protocol port).
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener listen = new TcpListener(localAddr, 80);

try
{
// Start listening
listen.Start();
Byte[] bytes = new byte[256];
TcpClient client = listen.AcceptTcpClient();
// This waits until we getting a connection
NetworkStream stream = client.GetStream();

int i;
String data = null;

while (stream.DataAvailable)
{
i = stream.Read(bytes, 0, bytes.Length);
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
txtMessages.Text += data.ToString();
}
client.Close();
}
catch (SocketException exceptionError)
{
MessageBox.Show(exceptionError.Message);
}
finally
{
listen.Stop();
}
}
Post a Comment