带有二进制/ byte []流的SocketAsyncEventArgs

时间:2017-06-19 16:15:31

标签: c# sockets stream socketasynceventargs

我是C#和套接字的新手,所以如果我的问题不合适,我会道歉。我开始使用此链接中的示例构建套接字接口: https://code.msdn.microsoft.com/High-Performance-NET-69c2df2f

我希望能够在套接字上传输二进制文件,所以我做了一个假设(可能是错误的)我不应该使用StringBuilder。我将OSUserToken更改为原始版本,使用MemoryStreamBinaryWriter(注释掉原始代码)。

在代码的其他位置(来自上面的链接),SocketAsyncEventArgs已使用SetBuffer(new Byte[_bufferSize], 0, _bufferSize);初始化。我担心这与我的MemoryStreamBinaryWriter不能很好地融合,但它似乎有效。

sealed class UserToken : IDisposable
{
    private Socket _ownerSocket;
    public Socket ownerSocket { get { return _ownerSocket; } }

    private MemoryStream _memoryStream;
    private BinaryWriter _binaryWriter;
    //private StringBuilder stringbuilder;

    private int totalByteCount;

    public String LastError;

    public UserToken(Socket readSocket, int bufferSize)
    {
        _ownerSocket = readSocket;
        _memoryStream = new MemoryStream();
        _binaryWriter = new BinaryWriter(_memoryStream);
        //stringbuilder = new StringBuilder(bufferSize);
    }

    // Do something with the received data, then reset the token for use by another connection.
    // This is called when all of the data have been received for a read socket.
    public void ProcessData(SocketAsyncEventArgs args)
    {
        String received = System.Text.Encoding.ASCII.GetString(_memoryStream.ToArray());
        //String received = stringbuilder.ToString();

        Debug.Write("Received: \"" + received + "\". The server has read " + received.Length + " bytes.");

        _memoryStream.SetLength(0);
        //stringbuilder.Length = 0;
        totalByteCount = 0;
    }

    public bool ReadSocketData(SocketAsyncEventArgs readSocket)
    {
        int byteCount = readSocket.BytesTransferred;

        /*
        if ((totalByteCount + byteCount) > stringbuilder.Capacity)
        {
            LastError = "Receive Buffer cannot hold the entire message for this connection.";
            return false;
        }
        else
        {
        */
            //stringbuilder.Append(Encoding.ASCII.GetString(readSocket.Buffer, readSocket.Offset, byteCount));
            _binaryWriter.Write(readSocket.Buffer,readSocket.Offset,byteCount);
            totalByteCount += byteCount;
            return true;
        /*}*/
    }

    public void Dispose()
    {
        _memoryStream.Dispose();
        _binaryWriter.Dispose();
        try
        {
            _ownerSocket.Shutdown(SocketShutdown.Both);
        }
        catch
        {
            //Nothing to do here, connection is closed already
        }
        finally
        {
            _ownerSocket.Close();
        }
    }
}

当我运行它时,似乎没有问题。即使我设置protected const int DEFAULT_BUFFER_SIZE = 1,它也会接受> 1字节的流:

17:11:20:433 - Debug - Initializing the listener on port 5000...
17:11:20:439 - Debug - Starting the listener...
17:11:20:444 - Debug - Server started.
17:11:31:856 - Debug - Received: "listener". The server has read 8 bytes.
17:11:33:264 - Debug - Received: "l". The server has read 1 bytes.
17:11:33:268 - Debug - Received: "istener". The server has read 7 bytes.
17:11:36:744 - Debug - Received: "l". The server has read 1 bytes.
17:11:36:744 - Debug - Received: "i". The server has read 1 bytes.
17:11:36:746 - Debug - Received: "stener". The server has read 6 bytes.

我的问题是这些:

  1. 我是对的StringBuilder对二进制文件不起作用我应该使用MemoryStreamBinaryWriter吗?
  2. 我是否需要关注程序中其他位置的缓冲区溢出,SocketAsyncEventArgs是否已使用SetBuffer(new Byte[_bufferSize], 0, _bufferSize);进行初始化?
  3. 如果我必须遵守缓冲区大小限制,我是否需要在发送数据的客户端上设置相同的缓冲区限制?

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案

  1. StringBuilder运行正常。只需在发送前对base64中的字符串进行编码,然后在接收后进行解码。无论是发送文本还是二进制数据,都应该这样做。参见我在下面写的课程。
  2. 仍然不知道这个问题的答案,但看到StringBuilder &安培; base64与二进制文件一起使用,此问题已不再适用。
  3. 我认为这个问题的答案是肯定的。客户端应具有最大消息长度。我正在根据套接字的标题部分进行控制,我在其中定义了消息的长度。标题是固定长度,我的最大消息长度是0xFFFFF
  4. 编码/解码base64的类:

    public static class Base64
    {
        public static string EncodeBase64(string text)
        {
            return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
        }
    
        public static string EncodeBase64(byte[] array)
        {
            return System.Convert.ToBase64String(array);
        }
    
        public static string DecodeBase64ToString(string base64String)
        {
            return System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(base64String));
        }
    
        public static Byte[] DecodeBase64ToBinary(string base64String)
        {
            Byte[] bytes = System.Convert.FromBase64String(base64String);
            return bytes;
        }
    }