Accepts a pending connection request : TCP Server « Network « C# / C Sharp






Accepts a pending connection request

 

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class TcpListenerSample
{
    static void Main(string[] args)
    {
            TcpListener server = new TcpListener(IPAddress.Any, 13000);
            server.Start();
            while (true)
            {
                byte[] bytes = new byte[1024];
                string data;

                TcpClient client = server.AcceptTcpClient();
                NetworkStream stream = client.GetStream();
                int i = stream.Read(bytes, 0, bytes.Length);
                while (i != 0)
                {
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine(String.Format("Received: {0}", data));
                    data = data.ToUpper();
                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
                    stream.Write(msg, 0, msg.Length);
                    Console.WriteLine(String.Format("Sent: {0}", data));
                    i = stream.Read(bytes, 0, bytes.Length);
                }
                client.Close();
            }

            Console.WriteLine("Hit enter to continue...");
            Console.Read();
    }
}

   
  








Related examples in the same category

1.Bad Tcp ServerBad Tcp Server
2.Fixed Tcp Server
3.Stream Tcp Server
4.Simple Tcp Server
5.Var Tcp Server
6.Employee Server
7.Network Order Server
8.Tcp Listener Sample
9.Async Tcp ServerAsync Tcp Server
10.Select Tcp Server
11.Tcp Poll Server
12.Threaded Tcp Server
13.Picky Tcp Listener
14.TcpListener Class