Data transfer between client and server

I'm trying to send a few strings of text from a client program to a server program, I am currently using the following code:

Client (Sending)

            public void netSend(string server,string category,string details,string computername,string username,string winversion)
            {
                  string[] sArray = {server, category, details, computername, username, winversion};
                  Socket client = null;
                  try
                  {
                        client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                        int servport = Int32.Parse("5024");
                        IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(server),servport);
                        client.Connect(serverEndPoint);
                        foreach (string dString in sArray)
                        {
                              byte[] clientbuffer = Encoding.ASCII.GetBytes(dString);
                              client.Send(clientbuffer,0,clientbuffer.Length,SocketFlags.None);
                        }
                  }
                  catch(Exception clienterror)
                  {
                        MessageBox.Show(clienterror.Message);
                  }
                  finally
                  {
                        client.Close();
                  }
            }

Server (Recieving)

            public void dataColl()
            
            {
                  Socket server = null;
                  try
                  {
                        server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                        server.Bind(new IPEndPoint(IPAddress.Any,5024));
                        server.Listen(5);
                  }
                  catch(SocketException se)
                  {
                        MessageBox.Show(se.ErrorCode + ": " + se.Message);
                        Environment.Exit(se.ErrorCode);
                  }
                  byte[] databuffer = new byte[buffersize];
                  for (;;)
                  {
                        Socket client = null;

                        try
                        {
                              client = server.Accept();
                              System.Windows.Forms.ListViewItem main = new System.Windows.Forms.ListViewItem(client.RemoteEndPoint.ToString());
                              string[] sArray = new string[7];
                                    for(int i=0; i < sArray.Length; i++)
                                    {
                                          client.Receive(databuffer,0,databuffer.Length,SocketFlags.None);
                                          sArray[i] = databuffer.ToString();
                                    }
                              DataReader.Write(sArray[0],sArray[1],sArray[2],sArray[3],sArray[4],sArray[5],sArray[6],sArray[7],"Yes",1,"");
                        }
                        catch(Exception servererror)
                        {
                              MessageBox.Show(servererror.Message);
                        }
                        finally
                        {
                              client.Close();
                        }
                  }
            }

(The buffersize is set with "private const int buffersize = 32;")

The text I recieve is garbled. I think the issue is timing related, the server code runs constantly in a separate thread. What am I doing wrong? Is it easier to use streamreader and streamwriter and what is packet framing?

Only 110 points...it's all I have, sorry.
LVL 1
pab89Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

philowareCommented:
//***change this line
byte[] clientbuffer = Encoding.ASCII.GetBytes(dString);
//***with this line
byte[] clientbuffer = Encoding.Unicode.GetBytes(dString+"\0");

//***change this line
 sArray[i] = databuffer.ToString();
//***with this line
sArray[i] = Encoding.Unicode.GetString( databuffer).Split('\0')[0];
pab89Author Commented:
Better...but not quite. The strings are still being split in the wrong places. It's as if they're being put into the array before the whole string has been recieved. Is this something to do with the buffer size since I don't know how large the recieved strings will be.
philowareCommented:
So we should write a more professional one:)
Let's specify a protocol...
We will first send the size of the string(or data) which is 4 bytes long
Then we will send the data

First we need a method which will read the data which is exactly the given size.
private void ReadData(Socket socket, ref byte []buffer, int dataSize)
{
  int size,index = 0;
 
  if(buffer == null || buffer.Length < dataSize)
   buffer = new byte[dataSize];
      
  while(dataSize > 0)
  {                  
      size = socket.Receive(buffer,index,dataSize,SocketFlags.None);
      if(size == 0)
            throw(new Exception("Connection closed"));
      dataSize -= size;
      index += size;                              
   }
}

Then let's write a new which will use ReadData method to receive data according to our protocol

private int ReadDataPro(Socket socket, ref byte []buffer)
{
 //**first read the size of the data
 ReadData(socket, ref buffer, 4);
 int dataSize = BitConverter.ToInt32(buffer, 0);
 //**then read the data
 ReadData(socket, buffer, dataSize);
 return dataSize;
}

//And now we will write the sender method

private void SendDataPro(Socket socket, byte []buffer, int dataSize)
{
  byte []sizeBuffer = BitConverter.GetBytes(dataSize);
  //send the dataSize
  socket.Send(sizeBuffer,0,4,SocketFlags.None);
  //sen the data
  socketSend(buffer,0,dataSize,SocketFlags.None);
}

//***now for the below part of your code you can use my code
 client.Receive(databuffer,0,databuffer.Length,SocketFlags.None);
 sArray[i] = databuffer.ToString();
//***here is my code
int dataSize = ReadDataPro(client/*socket*/, dataBuffer);
sArray[i] = Encoding.Unicode.GetString( databuffer, 0, dataSize);

//***and let's write an example for sending data
//***here is your code
 byte[] clientbuffer = Encoding.ASCII.GetBytes(dString);
 client.Send(clientbuffer,0,clientbuffer.Length,SocketFlags.None);
//***and here is my code
byte[] clientbuffer = Encoding.Unicode.GetBytes(dString);
SendDataPro(client, clientBuffer, clientBuffer.Length);

I think this answer is worth 2000 points but it doesn't matter;)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

pab89Author Commented:
Looks good, upped the points to 115 :P Just one problem, this line doesn't compile:

                  //**first read the size of the data
                  ReadData(socket, ref buffer, 4);
                  int dataSize = BitConverter.ToInt32(buffer, 0);
                  //**then read the data
            --->>  ReadData(socket, buffer, dataSize);
                  return dataSize;

I could make it work by changing that to "ref buffer" but I'm not sure if that's entirely a good thing.
philowareCommented:
Yes, as you see it must be ref. I forgot it.
philowareCommented:
And this one must be ref, too.
int dataSize = ReadDataPro(client/*socket*/, ref dataBuffer);
pab89Author Commented:
Ok, I'll give this a go. Thanks.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.