繁体   English   中英

如何在不创建新数组的情况下用字符串填充字节数组?

[英]How can i fill a byte array with a string without creating a new array?

我正在尝试打开多个websocket,我需要以某种方式在每个套接字上使用相同的缓冲区,或者在发送/接收新消息之前清除它们。 接收方法很好,因为我可以传递字节数组的参数,它将填充该参数而无需创建新的字节数组实例。

我该如何使用BitConverter.GetBytes方法?我需要开始使用不安全的上下文并使用带有指针参数的重载GetBytes吗?还有其他方法吗? 我需要它来填充将在构造函数中定义的outBytes变量。

public class Client:IDisposable
{
    //Fields
    public char[] innerData { get; private set; }

    private byte[] inBytes;
    private byte[] outBytes;

    private ArraySegment<byte> inSegment;
    private ArraySegment<byte> outSegment;


    private WebSocket webSocket;
    public WebSocket Socket => this.webSocket;

    public readonly string clientID;
    //Auxiliary
    private const int BufferSize = 1024;

    public static Client CreateClient(WebSocket socket, string id)
    {
        Client client = new Client(socket, id);

        return client;
    }

    public Client(WebSocket socket, string id)
    {
        this.inBytes = new byte[BufferSize];
        this.inSegment = new ArraySegment<byte>(inBytes);

        this.outBytes = new byte[BufferSize];
        this.outSegment = new ArraySegment<byte>(outBytes);


        this.webSocket = socket;
        this.clientID = id;
        this.innerData = new char[BufferSize];
    }
    public  async Task<WebSocketReceiveResult> ReceiveResult()
    {
        if(this.webSocket.State!=WebSocketState.Open)
        {
            return null;
        }

        WebSocketReceiveResult result = await this.webSocket.ReceiveAsync(this.inSegment, CancellationToken.None);
        Encoding.UTF8.GetChars(this.inSegment.Array, 0, BufferSize, this.innerData, 0);
        return result;
    }

    public async Task SendMessage(string message)
    {
        if(this.webSocket.State==WebSocketState.Open)
        {

            this.outBytes = Encoding.UTF8.GetBytes(message, 0, message.Length); //How can i fill the already existing outBytes?
            await this.webSocket.SendAsync(this.outSegment, WebSocketMessageType.Text, true, CancellationToken.None);
        }

    }

    public void Dispose()
    {
        if(this.webSocket.State!=WebSocketState.Closed)
        {
            this.webSocket.Dispose();
            this.webSocket = null;
        }
    }


}

我需要以某种方式利用现有outBytes当我转换的消息,我将send.At此刻outBytes的行为就像一个指针,并在每一个方法的SendMessage的每一次迭代GetBytes将产生一个新的字节数组。

您显然对GetBytes的工作方式有误解,它不会每次都生成新的数组,此重载:

Encoding.GetBytes方法(字符串,Int32,Int32,Byte [],Int32)

将指定字符串中的一组字符编码为指定字节数组(来自MSDN)

所以你的线应该是

Encoding.UTF8.GetBytes(message, 0, message.Length, this.outBytes, 0);

该函数将把使用UTF8编码转换为字节的字符串填充到数组中,然后您可以使用返回值(它是整数)来检查已将多少字节写入到数组中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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