Hy guys, this is how my client and server code looks like:
Client:
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("192.168.1.12"), 5004);
NetworkStream stream = client.GetStream();
string username = loginName_txt.Text;
byte[] message = Encoding.ASCII.GetBytes(username);
stream.Write(message, 0, message.Length);
loginName_txt.Clear();
string password = password_txt.Text;
byte[] message1 = Encoding.ASCII.GetBytes(password);
stream.Write(message1, 0, message1.Length);
password_txt.Clear();
stream.Close();
client.Close();
Server:
TcpClient mClient = (TcpClient)client;
NetworkStream stream = mClient.GetStream();
byte[] message = new byte[1024];
int recv = stream.Read(message, 0, message.Length);
username = Encoding.ASCII.GetString(message, 0 , recv);
updateUI("Username: " + Encoding.ASCII.GetString(message, 0, recv));
byte[] message1 = new byte[1024];
int recv1 = stream.Read(message1, 0, message1.Length);
password = Encoding.ASCII.GetString(message1, 0, recv1);
updateUI("Password: " + Encoding.ASCII.GetString(message1, 0, recv1));
stream.Close();
mClient.Close();
I'm trying to send the username and password as strings from the client to the server, but the problem is that i receive both strings as one on the server side, stored in "message". I know that somehow i should recognize the end of the first string and put in the the first array and after that start from there and put the other one into the second array, but i don`t know how to do it. I would like to ask you if could help me to solve this problem.
The problem is that you're using a stream-based protocol (TCP/IP) as if it were a message-based protocol. It's not. There are a few options here, but the simplest are:
The latter is what I generally prefer - it means that you always know exactly how much data you need to read before you start reading it, which means you can tell when you're done, and you know what size of array to allocate before you start reading, too. Oh, and it also means there's no need to escape anything, whereas if you have a delimiter which could naturally occur within a message, that would need escaping.
See more on this question at Stackoverflow