Avatar of Brad Brett
Brad Brett
Flag for United States of America asked on

Best way to use Sockets in C#

I have seen a lot of ways to deal with sockets in VB.NET, however I am not sure which way is the best way that allow:
1. Sending string data (both sides)
2. Sending binary data (both sides, including large binary data and files)

Important: I DONT want to know how to use Sockets, I already know that.

I want the best way to use to achieve what I said above.

Basically I want the following methods to be included:
sendData();
sendFile();

I want to be using TcpListener/TcpClient.

The problem I usually face is when I have 1025 bytes buffer and I receive for example two binary buffers, one use the full 1025 and the other use for example 400 bytes from 1024, so if i wrote that to a file it will write about 2050 which is invalid file size, the file size is only 1425 bytes.
Microsoft Development.NET ProgrammingVisual Basic.NETC#

Avatar of undefined
Last Comment
Brad Brett

8/22/2022 - Mon
BuggyCoder

make your methods look like this on receiving end:-
public void ReceiveData(byte[] arrBytes);
public void ReceiveFile(FileStream stream);

Open in new window

Brad Brett

ASKER
@BuggyCoder: Can you give an example or sample code? Usually I receive the data in bytes and converting bytes to FileStream, I think it will keep unnecessary data at the end.

Another thing is sending Binary data, could be 10 MB of binary data but its NOT a file.

Thanks,
BuggyCoder

even in case of file as well, just use the first method.
Just make sure that on the other end send your file as stream of bytes....

here is a link to convert filestream to byte array:-
http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx
Your help has saved me hundreds of hours of internet surfing.
fblack61
Nasir Razzaq

>The problem I usually face is when I have 1025 bytes buffer and I receive for example two binary buffers, one use the full 1025 and the other use for example 400 bytes from 1024, so if i wrote that to a file it will write about 2050 which is invalid file size, the file size is only 1425 bytes.


Have you tried using the stream.length property to determine the size of data instead of using 1024 bytes?


http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx
Brad Brett

ASKER
@CodeCruiser: I am not sure where to use stream.

I want someone to modify the following code to solve the problem (please see the comments in the code):

// Public Declaration
bytes[] buff = new bytes[1024];

// This line is used after connection
tcpClient.Client.BeginReceive(buff, 0, buff.Length, SocketFlags.None, DataReceived, null);

void DataReceived()
{
      // Here you can process the buffer you have received...
      // EXAMPLE: string str = Encoding.ASCII.GetString(buff);
      // The problem I usually get here because buff contains 1025 bytes of data EVEN if the server sent only 50 bytes.

      // Receive more data
      tcpClient.Client.BeginReceive(buff, 0, buff.Length, SocketFlags.None, DataReceived, null);
}

Open in new window

ASKER CERTIFIED SOLUTION
Nasir Razzaq

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Brad Brett

ASKER
@CodeCruiser: Can you please update the sample code that I posted earlier.

Thanks,
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Nasir Razzaq

Where is your endreceive code?
Brad Brett

ASKER
I am not using endreceive code yet, the code I am using is similar to the one I posted earlier:
// Public Declaration
bytes[] buff = new bytes[1024];

// This line is used after connection
tcpClient.Client.BeginReceive(buff, 0, buff.Length, SocketFlags.None, DataReceived, null);

void DataReceived()
{
      // Here you can process the buffer you have received...
      // EXAMPLE: string str = Encoding.ASCII.GetString(buff);
      // The problem I usually get here because buff contains 1025 bytes of data EVEN if the server sent only 50 bytes.

      // Receive more data
      tcpClient.Client.BeginReceive(buff, 0, buff.Length, SocketFlags.None, DataReceived, null);
}

Open in new window


I only need to update that code to get the result I asked for.

Thanks,
SOLUTION
hjgode

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
sarabande

for variable sized data via sockets you normally would pass a fixed-sized "header" prior to the data. the header contains (at least) the length of the data in bytes as first information. often you also would add sender information or some type of message and put them all to a  structure. the structure must have same alignment and size on all platforms (simply use 32-bit integer type for all members). then your receive function firstly would read until the full header was read. if sender and receiver could be on different endian platforms the sender would convert all integer members to "network order" what is big-endian. there are platform-specific functions htons (for 16-bit integer) and htonl (32-bit) which do that job. after you received the full header you would reconvert the integer length by calling ntohl. after you know the length of the data stream you could allocate an appropriate buffer and read in a loop until error or until all data was received.

Sara
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
hjgode

Hi

I aggree to the way sarabande describes a bniary socket transfer. It is also a good idea, to describe the length of the data first and possibly to add some CRC or similar error checking.

That leads to your first question, if it is better to use strings or bytes to transfer data via sockets. If you go with strings, you may have to control the way unicode or UTF8 strings are converted to/from byte arrays, as finally, sockets only transfer bytes. You have also to consider, how the end of a string is marked (normally with one or two (unicode) null byte(s)). Or you add some marker to the end like "<EOT>".

But finally, you end up with reading bytes in chunks until all bytes are read. You have to re-assemble the bytes back to a large array or a string.

~josef
Brad Brett

ASKER
I have been busy with other projects in other programming languages, so I didn't get a chance to even try the solution here, using EndReceive() works perfectly!

Thanks,