Picky Tcp Listener : TCP Server « Network « C# / C Sharp






Picky Tcp Listener

 
/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/

using System;
using System.Net;
using System.Net.Sockets;
using System.Security;
using System.Security.Permissions;
using System.Text;

[SocketPermission(SecurityAction.Deny, Access="Accept", Host="0.0.0.0",
      Port="9050", Transport="All")]
[SocketPermission(SecurityAction.Deny, Access="Accept", Host="0.0.0.0",
      Port="9051", Transport="All")]
[SocketPermission(SecurityAction.Deny, Access="Accept", Host="0.0.0.0",
      Port="9052", Transport="All")]

public class PickyTcpListener
{
   public static void Main()
   {
      int recv;
      TcpListener newsock = null;
      byte[] data = new byte[1024];

      Console.Write("Enter port number to use: ");
      string stringPort = Console.ReadLine();
      int port = Convert.ToInt32(stringPort);

      try
      {
         newsock = new TcpListener(port);
         newsock.Start();
      } catch (SecurityException)
      {
         Console.WriteLine("Sorry, that port is unavailable");
         return;
      }
      Console.WriteLine("Waiting for a client...");

      TcpClient client = newsock.AcceptTcpClient();
      NetworkStream ns = client.GetStream();

      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      ns.Write(data, 0, data.Length);

      while(true)
      {
         data = new byte[1024];
         recv = ns.Read(data, 0, data.Length);
         if (recv == 0)
            break;
       
         Console.WriteLine(
                  Encoding.ASCII.GetString(data, 0, recv));
         ns.Write(data, 0, recv);
      }
      ns.Close();
      client.Close();
      newsock.Stop();
   }
}

           
         
  








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.TcpListener Class
14.Accepts a pending connection request