title: How to send an object through a socket C#
body: <p>I have a list of objects and I want to sent it thought TCP socket connection. One way is to take the object list and get all the values separating them by comas and the receiving data and on the other end and values in a object. Can I send a object list as it can be done in WCF web service. It so can you show me how? Thanks!</p>
  
  <p>I did already created a WCF Service for this but changed it as it has a few issues that can't be solved. So I am creating this Client server application.</p>
  
  <p>Also the data that is being send is refreshed every few seconds, and it will be needed by a lot of users. After some research I found out this would be a better option.</p>
  
  <p>I have this class with which I was sending my messages through</p>
  
  <pre><code>public void SendMessage(string text)
  {
      Byte[] bytesSent = Encoding.UTF8.GetBytes(text);
      SocketAsyncEventArgs writeEventArgs = new SocketAsyncEventArgs();
      writeEventArgs.SetBuffer(bytesSent, 0, bytesSent.Length);
      socket.SendAsync(writeEventArgs);
  }
  </code></pre>
  
  <p>But I would out rather serialize the object first and then send it. So I have a stream and need as a byte array.</p>
  
  <p>This what I have to receive data:</p>
  
  <pre><code>void ReceiveData()
  {
      try
      {
          int recv;
          string stringData;
          while (true)
          {
              recv = socket.Receive(data);
              stringData = Encoding.ASCII.GetString(data, 0, recv);
              if (stringData == "bye")
                  break;
              ClientDataRecievedEventArgs sd = new ClientDataRecievedEventArgs(stringData);
              DataRecieved(this, sd);
          }
          stringData = "bye";
          byte[] message = Encoding.ASCII.GetBytes(stringData);
          socket.Send(message);
          socket.Close();
          this.Dispose();
          return;
      }
      catch (Exception)
      {
          socket.Close();
          this.Dispose();
      }
  
  }
  </code></pre>
  
  <p>This is want I am using:</p>
  
  <pre><code>SoapFormatter formatter = new SoapFormatter();
  
  foreach (Communication.Client Client in server.ClientList)
  {
      foreach (ObjectLibrary.Model.PIP p in Repository.GlobalRepository.PIPInformation)
      {
  
          formatter.Serialize(stream, p);
          Client.SendMessage(stream);
      }
  }
  </code></pre>
  
  <p>How do I initialize the stream?
  I need to get the data as Stream to deserialize it to Object.</p>
  
  <p>And so I have list of Objects Can I serialize a whole list?</p>