Cents02
Cents02

Reputation: 77

How to avoid specifying byte array length when waiting for an input using TCP and sockets

Problem:
I'm making a small app in which, when ran it has a login page requiring the user to enter username and password. When these are entered, the information goes to the server via TCP using sockets. However, from what I found online, in order to do so you need to specify a length of bytes in order to receive the information (see code below). The problem is that when I specify the length the rest of the string becomes \0\0\0 until all the byte slots are filled which causes problems later in the process.

What I tried:
I have tried removing the part "\0\0\0.." from the string but it failed as the program kept failing on finding the character "\". I'm not if I'm using the correct protocol or method for this but any advice is welcomed.

NetworkStream stream = client.GetStream(); //Gets input stream
            byte[] receivedBuffer = new byte[100]; 
            stream.Read(receivedBuffer, 0, receivedBuffer.Length);
            string msg = Encoding.ASCII.GetString(receivedBuffer,0,receivedBuffer.Length); //translates msg

            if(msg.Contains("|")) //if the msg contains "|" = log-in
                {
                bool cr1 = false;
                bool cr2 = false;
                string[] cre = msg.Split("|");

                if(cre[0] == "admin") //the whole checking system will be made properly and I know this is wrong but its for testing
                {
                    cr1 = true;
                }
                if (cre[1] == "pass")
                {
                    cr2 = true;
                }

                if (cr1 == true && cr2 == true)
                {
                    string answer = "True";
                    Tosend(answer); //Sends response to client
                }
                else
                {
                    string answer = "False";
                    Tosend(answer);
                }
                }

Class to send things:
static void Tosend(string msg)
{
string ip3 = "localhost";
TcpClient client = new TcpClient(ip3, 8081);
int bc = Encoding.ASCII.GetByteCount(msg);
byte[] sd = new byte[bc];
sd = Encoding.ASCII.GetBytes(msg);
NetworkStream st = client.GetStream();
st.Write(sd, 0, sd.Length);
st.Close();
client.Close();
}

EXAMPLE
What I get:
Input: user|pass => to bytes => Sends bytes => Bytes received => Bytes translated => msg = user|pass\0\0\0\0\0\0\0\0...
Expectation:
Input: user|pass => to bytes => Sends bytes from client => Bytes received by server => Bytes translated => msg = user|pass

Upvotes: 0

Views: 478

Answers (1)

N.D.C.
N.D.C.

Reputation: 1601

NetworkStream.Read will return the number of bytes read. You can use that to pull out only the actual data.

int receivedBytes = stream.Read(receivedBuffer, 0, receivedBuffer.Length);
string msg = Encoding.ASCII.GetString(receivedBuffer,0,receivedBytes);

Upvotes: 1

Related Questions