我正在尝试打开多个websockets,我需要以某种方式在每个插槽中使用相同的缓冲区或在发送/接收新消息之前清除它们。 接收方法很好,因为我可以传递一个字节数组的参数,它将填充那个参数而不创建一个新的字节数组实例。
我可以用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
。此时outBytes
的行为类似于指针,并且每次迭代时都会发送SendMessage方法GetBytes
将生成一个新的字节数组。
答案 0 :(得分:2)
你显然对GetBytes如何工作有误解,它不会每次都生成一个新数组,这个重载:
Encoding.GetBytes Method (String, Int32, Int32, Byte[], Int32)
将
将指定字符串中的一组字符编码为指定的字节数组(来自MSDN)
所以你的行应该是
Encoding.UTF8.GetBytes(message, 0, message.Length, this.outBytes, 0);
该函数将使用UTF8编码将此字符串转换为字节来填充您的数组... 并且您可以使用返回值(一个整数)来检查已将多少字节写入数组。