title: TCP client in ASP.net
body: <p>i'm trying to connect from asp web application to tcp server. I did this using application in C#, and now i'd like to see if it will be working from web browser.</p>
  
  <p>My code is: </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Text;
  using System.Net;
  using System.Net.Sockets;
  
  namespace TcpWebClient
  
  {
      public partial class _Default : System.Web.UI.Page
  {
  
      private byte[] data = new byte[1024];
      IPEndPoint ipep = new IPEndPoint(
              IPAddress.Parse("192.168.1.20"), 12000);
  
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Stream, ProtocolType.Tcp);
  
  
      protected void Page_Load(object sender, EventArgs e)
      {
  
      }
  
      protected void Button1_Click(object sender, EventArgs e)
      {
  
          try
          {
              server.Connect(ipep);
          }
          catch (SocketException)
          {              
          }
      }
  
      protected void Button2_Click(object sender, EventArgs e)
      {
          NetworkStream ns = new NetworkStream(server);
  
          if (ns.CanWrite)
          {
              ns.Write(Encoding.ASCII.GetBytes("DI"), 0, 2);
              ns.Flush();
          }
          else
          {
          }
          TextBox1.Text = null;
          TextBox1.Text = Encoding.ASCII.GetString(data, 0, ns.Read(data, 0, data.Length));
      }
  
  }
  }
  </code></pre>
  
  <p>What is working?: I have connection to tcp server. But when i want to send and receive some data i'm getting errors: </p>
  
  <pre><code>IOException was unhandled by user code and something like this: Operation is not supported on connected sockets (don't know if my translation to english is ok).
  </code></pre>
  
  <p>What i'm doing wrong?</p>
  
  <p>A first chance exception of type 'System.IO.IOException' occurred in System.dll</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Something like this is working.. but every tick of timer i need to reconnect to the server.. is it possible to have one connection, then every tick of timer read/send data without reconnecting?</p>
  
  <pre><code> protected void Timer1_Tick(object sender, EventArgs e)
      {
  
              server.Connect(ipep);
              NetworkStream stream = new NetworkStream(server);
  
              Byte[] data = System.Text.Encoding.ASCII.GetBytes("data");
              stream.Write(data, 0, data.Length);
              data = new Byte[256];
              Int32 bytes = stream.Read(data, 0, 8);
              responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
              TextBox1.Text = responseData;
              server.Close();
  
          }
  </code></pre>