简体   繁体   中英

C# Separate TCP messages

I'm working on a TCP Client/Server system for practice purposes and I want to send specific data between the two.

I'm already able to send bytes and let them display as a string. Also I am able to send a specific string ("mb") and let a MessageBox pop-up on the server-side.

The content of the Box is the text sent (in this case "mb", though).

This is the Server-Side:

byte[] msg = new byte[4096];

var count = stream.Read(msg, 0, msg.Length);
string returnData = Encoding.ASCII.GetString(msg, 0, count);

switch(returnData)
{
    case "mb":                            
        MessageBox((IntPtr)0, returnData, "HACKERZ", 0);
             break;
    case "":                            
            client.Client.Disconnect(true);                        
        Console.WriteLine("User disconnected");
             break;
    default:
        Console.WriteLine(returnData);
             break;
}      

And this is Client-Side:

private void btnSend_Click(object sender, EventArgs e)
{
    NetworkStream stream = client.GetStream();

    byte[] msg = new byte[4096];
    msg = Encoding.ASCII.GetBytes(txtMsg.Text);

    stream.Write(msg, 0, msg.Length);
}

So if I write "mb" in the Textfield, it shows a MessageBox saying "mb".

I would like to know, how can I separate the message that was sent by the NetworkStream, so I can set Capture and Content of the MessageBox separately.

As you noticed, you are sending binary data over socket. In client you get bytes from message msg = Encoding.ASCII.GetBytes(txtMsg.Text); and in server you're casting it back to string with string returnData = Encoding.ASCII.GetString(msg, 0, count);

In this approach, you can send for instance comma-separated string where first field would be Capture and second Content.

However, as it is byte stream, you can send anything what is serializable into bytes. You can use BinaryWriter\\BinaryReader over Network stream to send any structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM