Simple Tcp Server

   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SimpleTcpSrvr
{
   public static void Main()
   {
      int recv;
      byte[] data = new byte[1024];
      IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
                             9050);

      Socket newsock = new
          Socket(AddressFamily.InterNetwork,
                      SocketType.Stream, ProtocolType.Tcp);

      newsock.Bind(ipep);
      newsock.Listen(10);
      Console.WriteLine("Waiting for a client...");
      Socket client = newsock.Accept();
      IPEndPoint clientep =
                   (IPEndPoint)client.RemoteEndPoint;
      Console.WriteLine("Connected with {0} at port {1}",
                      clientep.Address, clientep.Port);

      
      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      client.Send(data, data.Length,
                        SocketFlags.None);
      while(true)
      {
         data = new byte[1024];
         recv = client.Receive(data);
         if (recv == 0)
            break;
       
         Console.WriteLine(
                  Encoding.ASCII.GetString(data, 0, recv));
         client.Send(data, recv, SocketFlags.None);
      }
      Console.WriteLine("Disconnected from {0}",
                        clientep.Address);
      client.Close();
      newsock.Close();
   }
}

           
          


Stream Tcp Server

   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class StreamTcpSrvr
{
   public static void Main()
   {
      string data;
      IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

      Socket newsock = new Socket(AddressFamily.InterNetwork,
                      SocketType.Stream, ProtocolType.Tcp);

      newsock.Bind(ipep);
      newsock.Listen(10);
      Console.WriteLine("Waiting for a client...");

      Socket client = newsock.Accept();
      IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
      Console.WriteLine("Connected with {0} at port {1}",
                      newclient.Address, newclient.Port);

      NetworkStream ns = new NetworkStream(client);
      StreamReader sr = new StreamReader(ns);
      StreamWriter sw = new StreamWriter(ns);

      string welcome = "Welcome to my test server";
      sw.WriteLine(welcome);
      sw.Flush();

      while(true)
      {
         try
         {
            data = sr.ReadLine();
         } catch (IOException)
         {
            break;
         }
       
         Console.WriteLine(data);
         sw.WriteLine(data);
         sw.Flush();
      }
      Console.WriteLine("Disconnected from {0}", newclient.Address);
      sw.Close();
      sr.Close();
      ns.Close();
   }
}

           
          


Fixed Tcp Server

/*
C# Network Programming
by Richard Blum

Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class FixedTcpSrvr
{
private static int SendData(Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;

while (total < size) { sent = s.Send(data, total, dataleft, SocketFlags.None); total += sent; dataleft -= sent; } return total; } private static byte[] ReceiveData(Socket s, int size) { int total = 0; int dataleft = size; byte[] data = new byte[size]; int recv; while(total < size) { recv = s.Receive(data, total, dataleft, 0); if (recv == 0) { data = Encoding.ASCII.GetBytes("exit "); break; } total += recv; dataleft -= recv; } return data; } public static void Main() { byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); Socket client = newsock.Accept(); IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); int sent = SendData(client, data); for (int i = 0; i < 5; i++) { data = ReceiveData(client, 9); Console.WriteLine(Encoding.ASCII.GetString(data)); } Console.WriteLine("Disconnected from {0}", newclient.Address); client.Close(); newsock.Close(); } } [/csharp]

Picky Tcp Client

   

/*
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="Connect", Host="127.0.0.1",
     Port="All", Transport="All")]
[SocketPermission(SecurityAction.Deny, Access="Connect", Host="192.168.0.2",
     Port="All", Transport="All")]
[SocketPermission(SecurityAction.Deny, Access="Connect", Host="192.168.1.100",
     Port="80", Transport="All")]


public class PickyTcpClient
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      TcpClient server = null;

      Console.Write("Enter a host to connect to: ");
      string stringHost = Console.ReadLine();
 
      try
      {
         server = new TcpClient(stringHost, 9050);
      } catch (SocketException)
      {
         Console.WriteLine("Unable to connect to server");
         return;
      } catch (SecurityException)
      {
         Console.WriteLine(
            "Sorry, you are restricted from connecting to this server");
         return;
      }
      NetworkStream ns = server.GetStream();

      int recv = ns.Read(data, 0, data.Length);
      stringData = Encoding.ASCII.GetString(data, 0, recv);
      Console.WriteLine(stringData);

      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
         ns.Flush();

         data = new byte[1024];
         recv = ns.Read(data, 0, data.Length);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      }
      Console.WriteLine("Disconnecting from server...");
      ns.Close();
      server.Close();
   }
}
           
          


Select Tcp Client

   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SelectTcpClient
{
   public static void Main()
   {
      Socket sock = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
      byte[] data = new byte[1024];
      string stringData;
      int recv;

      sock.Connect(iep);
      Console.WriteLine("Connected to server");
      recv = sock.Receive(data);
      stringData = Encoding.ASCII.GetString(data, 0, recv);
      Console.WriteLine("Received: {0}", stringData);


      while(true)
      {
         stringData = Console.ReadLine();
         if (stringData == "exit")
            break;
         data = Encoding.ASCII.GetBytes(stringData);
         sock.Send(data, data.Length, SocketFlags.None);
         data = new byte[1024];
         recv = sock.Receive(data);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine("Received: {0}", stringData);
      }
      sock.Close();
   }
}

           
          


Async Tcp Client


   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/

using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;


public class AsyncTcpClient : Form
{
   private TextBox newText;
   private TextBox conStatus;
   private ListBox results;
   private Socket client;
   private byte[] data = new byte[1024];
   private int size = 1024;

   public AsyncTcpClient()
   {
      Text = "Asynchronous TCP Client";
      Size = new Size(400, 380);
      
      Label label1 = new Label();
      label1.Parent = this;
      label1.Text = "Enter text string:";
      label1.AutoSize = true;
      label1.Location = new Point(10, 30);

      newText = new TextBox();
      newText.Parent = this;
      newText.Size = new Size(200, 2 * Font.Height);
      newText.Location = new Point(10, 55);

      results = new ListBox();
      results.Parent = this;
      results.Location = new Point(10, 85);
      results.Size = new Size(360, 18 * Font.Height);

      Label label2 = new Label();
      label2.Parent = this;
      label2.Text = "Connection Status:";
      label2.AutoSize = true;
      label2.Location = new Point(10, 330);

      conStatus = new TextBox();
      conStatus.Parent = this;
      conStatus.Text = "Disconnected";
      conStatus.Size = new Size(200, 2 * Font.Height);
      conStatus.Location = new Point(110, 325);

      Button sendit = new Button();
      sendit.Parent = this;
      sendit.Text = "Send";
      sendit.Location = new Point(220,52);
      sendit.Size = new Size(5 * Font.Height, 2 * Font.Height);
      sendit.Click += new EventHandler(ButtonSendOnClick);

      Button connect = new Button();
      connect.Parent = this;
      connect.Text = "Connect";
      connect.Location = new Point(295, 20);
      connect.Size = new Size(6 * Font.Height, 2 * Font.Height);
      connect.Click += new EventHandler(ButtonConnectOnClick);

      Button discon = new Button();
      discon.Parent = this;
      discon.Text = "Disconnect";
      discon.Location = new Point(295,52);
      discon.Size = new Size(6 * Font.Height, 2 * Font.Height);
      discon.Click += new EventHandler(ButtonDisconOnClick);
   }

   void ButtonConnectOnClick(object obj, EventArgs ea)
   {
      conStatus.Text = "Connecting...";
      Socket newsock = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream, ProtocolType.Tcp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
      newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
   }

   void ButtonSendOnClick(object obj, EventArgs ea)
   {
      byte[] message = Encoding.ASCII.GetBytes(newText.Text);
      newText.Clear();
      client.BeginSend(message, 0, message.Length, SocketFlags.None,
                   new AsyncCallback(SendData), client);
   }

   void ButtonDisconOnClick(object obj, EventArgs ea)
   {
      client.Close();
      conStatus.Text = "Disconnected";
   }

   void Connected(IAsyncResult iar)
   {
      client = (Socket)iar.AsyncState;
      try
      {
         client.EndConnect(iar);
         conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
         client.BeginReceive(data, 0, size, SocketFlags.None,
                       new AsyncCallback(ReceiveData), client);
      } catch (SocketException)
      {
         conStatus.Text = "Error connecting";
      }
   }

   void ReceiveData(IAsyncResult iar)
   {
      Socket remote = (Socket)iar.AsyncState;
      int recv = remote.EndReceive(iar);
      string stringData = Encoding.ASCII.GetString(data, 0, recv);
      results.Items.Add(stringData);
   }

   void SendData(IAsyncResult iar)
   {
      Socket remote = (Socket)iar.AsyncState;
      int sent = remote.EndSend(iar);
      remote.BeginReceive(data, 0, size, SocketFlags.None,
                    new AsyncCallback(ReceiveData), remote);
   }

   public static void Main()
   {
      Application.Run(new AsyncTcpClient());
   }
}
           
          


Tcp Client Sample

   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class TcpClientSample
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      TcpClient server;
 
      try
      {
         server = new TcpClient("127.0.0.1", 9050);
      } catch (SocketException)
      {
         Console.WriteLine("Unable to connect to server");
         return;
      }
      NetworkStream ns = server.GetStream();

      int recv = ns.Read(data, 0, data.Length);
      stringData = Encoding.ASCII.GetString(data, 0, recv);
      Console.WriteLine(stringData);

      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
         ns.Flush();

         data = new byte[1024];
         recv = ns.Read(data, 0, data.Length);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      }
      Console.WriteLine("Disconnecting from server...");
      ns.Close();
      server.Close();
   }
}