How to send integer array over a TCP connection in c#

前端 未结 5 1206
萌比男神i
萌比男神i 2021-01-06 04:01

I have established a TCP connection between two computers for sending and receiving data back and forth, in a windows application. The message that I am sending is a set of

5条回答
  •  青春惊慌失措
    2021-01-06 04:32

    Okay a simply suggestion you can use

    • Sender first send the length of integer array.

    • Receiver create an array to receive this data

    • Sender in a loop use WriteLine() to send each element of the array (As string or int)

    • Receiver in a loop use ReadLine() to catch each element. and convert received string to integer

    Sender :

    m_writer.WriteLine(myarray.Length); // Sender sends the array length prior to data transmission
    
    // Send all data
    foreach(int item in myarray){
          m_writer.WriteLine(item.ToString());
    }
    

    Receiver :

    int Size =Convert.ToInt32( m_reader.ReadLine()); //receiver receives the Length of incoming array 
    
    int i=0;
    // Receive all data
    while(i < Size){
         Console.WrilteLine(Convert.ToInt32(m_reader.ReadLine())); // Add this to array
         i++;
    }
    

提交回复
热议问题