blah blah blah is here! blah blah » Close

up0down
link

how do you convert an int Socket.Received to a string?

i get it received with the ascii number equivalents, but cannot convert those into a string

last answered one year ago

2 answers

up0down
link

The 'int' return value of Socket.Receive represents the number of bytes received.

The byte[] parameter ('buffer') will contain the bytes themselves and, assuming they're being sent in the usual UTF-8 format, you can convert them to a string with:

string s = System.Text.Encoding.UTF8.GetString(buffer);

up0down
link

remember that socket.Receive can only read in only as much as you have space in your buffer. I typically use an 8k byte array because that's the default size of the tcp stack. you need to test the byte count Receive returns against the original size of your buffer, and if the received bytes is less than the buffer size, you'll want to stop receiving and decode the entire set of bytes:

int count = 0;
byte[] buffer = new byte[8192];
List<byte> data = new List<byte>();
while( true ) {
count = socket.Receive( buffer );

if ( count != buffer.Length ) { // done getting everything
byte[] temp = new byte[count];
Array.Copy( buffer, temp, count );
data.AddRange( temp );
break;
} else { // not done getting stuff yet, continue to read
data.AddRange( buffer );
}
}
string message = Encoding.UTF8.GetString( data.ToArray( ) );
Console.WriteLine( message );


usually with a buffer of 8k you'll get it in the first iteration, but sometimes when the message being sent is really long, you'll have to do it several times.

Feedback