I'm sending to a device a request as byte array and I want to receive the anwser device gives.
...
Socket deviceSocket = new Socket(server);
List<byte> coming = new List<byte>();
...
deviceSocket.Receive(coming)
Here the program gives error:
Error 1
The best overloaded method match for 'System.Net.Sockets.Socket.Receive(byte[])' has some invalid arguments
Error 2
Argument '1': cannot convert from 'System.Collections.Generic.List' to 'byte[]'
How can I solve it ?
Thanks.
Dynamic arrays are resizable and provide random access for their elements. They can be initialized with variable size, and their size can be modified later in the program. Dynamic arrays are allocated on the heap whereas VLAs are allocated on the stack.
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
A dynamic array is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern programming languages. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that needs to be specified at allocation.
Dynamically allocated arrays are allocated on the heap at run time. The heap space can be assigned to global or local pointer variables that store the address of the allocated heap space (point to the first bucket).
as the error tells use byte[]
Socket deviceSocket = new Socket(server);
byte[] coming = new byte[buffersize];
...
deviceSocket.Receive(coming)
See also this
The Socket.Receive() method will fill a buffer with as much data as it can fit, or as much data is available, whichever is lower.
If you know all your messages are under 2048 bytes then you could declare your buffer as follows:
byte[] buffer = new byte[2048];
int bytesReceived = 0;
// ... somewhere later, getting data from client ...
bytesReceived = deviceSocket.Receive( buffer );
Debug.WriteLine( String.Format( "{0} bytes received", bytesReceived ) );
// now process the 'bytesReceived' bytes in the buffer
for( int i = 0; i < bytesReceived; i++ )
{
Debug.WriteLine( buffer[i] );
}
Of course you probably want to do something more than write the bytes to the debug output, but you get the idea :)
You still need to be aware that you may get incomplete data, if the client broke the message into multiple packets then one might come through (and be received) and then later another. It's always good to have some way of telling the server how much data to expect, then it can assemble the complete message before processing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With