简体   繁体   中英

Multithreading TCP

Guys so here is another thing.

    private void Form1_Load(object sender, EventArgs e)
    {
        sck.Connect("127.0.0.1", 8080);   
        int s = sck.Send(Encoding.Default.GetBytes("A" + "~" + "B" + "~" + "C" + "~" + "D"));
    }

is there a way to send them separately to the server? and also receive them and adding them separately into the listView without splitting? Below the clientdata is the whole integer from void Load Form

    void client_Received(Client sender, byte[] data)
    {
        Invoke((MethodInvoker)delegate
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                Client client = listView1.Items[i].Tag as Client;
                if (client.ID == sender.ID)
                {
                    clientdata = Encoding.Default.GetString(data); ;
                    string[] str = clientdata.Split('~');
                    listView1.Items[i].SubItems[2].Text = str[0];
                    listView1.Items[i].SubItems[3].Text = str[1];
                    listView1.Items[i].SubItems[4].Text = str[2];
                    listView1.Items[i].SubItems[5].Text = str[3];
                    break;
                }
            }
        });
    }

i want to change this void something Like:

void client_Received(Client sender, byte[] A, byte[] B, byte[] C, byte[] D)
{

}

You make the classic false assumption that a socket Receive() s exactly what you Send() . This is not true, and that is why application protocols exist.

You will have to decide on a method of separating parameters and/or messages, which will be your application protocol. There are various ways of doing this, the easiest way is to start each message with an integer indicating the size in bytes of the following message.

This protocol has to be understood by both server and client in order to make them both communicate effectively. Once you've decided on your message format, create a parser for it. Then you can let your parser return any object you like, for example one that contains the four byte arrays you seem to be willing to send.

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