Proper sending and receiving via C# sockets?

前端 未结 3 925
轮回少年
轮回少年 2021-01-28 20:58

I\'m attempting to create a remote desktop server and client using C#. The server captures the screen and then sends it to the client via a socket. I\'m using the code below alt

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-28 21:43

    You must set a delimiter at the end of your image, some set of bytes that will sinalize the server that the image has ended. It's also known as end of file (EOF) or end of message. TCP won't split the image into logical packets for your app, so you must write your own control of information.

    The logic would be similar to this: CLIENT

    byte[] EndOfMessage = System.Text.Encoding.ASCII.GetBytes("image_end");
    byte[] ImageBytes = GetImageBytes();
    byte[] BytesToSend = new byte[EndOfMessage.Length + ImageBytes.Length];
    Array.Copy(ImageBytes, 0, BytesToSend);
    Array.Copy(EndOfMessage, 0, BytesToSend, ImageBytes.Length, EndOfMessage.Length);
    
    SendToServer(BytesToSend);
    

    SERVER

    byte[] EndOfMessage = System.Text.Encoding.ASCII.GetBytes("image_end");
    byte[] ReceivedBytes;
    
    while(!IsEndOfMessage(ReceivedBytes, EndOfMessage ))
    {
    //continue reading from socket and adding to ReceivedBytes
    }
    
    ReceivedBytes = RemoveEndOfMessage(ReceivedBytes, EndOfMessage );
    PrintImage(ReceivedBytes);
    

    I'm at work right now and I can't provide a full running example, I'm sorry.

    Regards


    Support methods:

    private bool IsEndOfMessage(byte[] MessageToCheck, byte[] EndOfMessage)
    {
        for(int i = 0; i++; i < EndOfMessage.Length)
        {
            if(MessageToCheck[MessageToCheck.Length - (EndOfMessage.Length + i)] != EndOfMessage[i])
                return false;
        }
    
        return true;
    }
    
    private byte[] RemoveEndOfMessage(byte[] MessageToClear, byte[] EndOfMessage)
    {
        byte[] Return = new byte[MessageToClear.Length - EndOfMessage.Length];
        Array.Copy(MessageToClear, Return, Return.Length);
    
        return Return;
    }
    

    Again, I couldn't test them, so you may find some bugs.

提交回复
热议问题