所以,我意识到我一直被否决,因为这个问题并不简洁和可重复。所以我创建了一个小项目来演示问题的这一部分,具有讽刺意味的是,问题消失了。
这是代码:
public sealed partial class MainPage : Page
{
private StreamSocketListener _listener;
private StreamSocket _client;
private StreamSocket _socket;
private HostName _host;
private int _port = 54321;
public MainPage()
{
InitializeComponent();
_listener = new StreamSocketListener();
_listener.ConnectionReceived += async (sender, args) =>
{
_socket = args.Socket;
await Receive();
};
_host = NetworkInformation.GetHostNames().FirstOrDefault(x => x.IPInformation != null && x.Type == HostNameType.Ipv4);
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
await _listener.BindEndpointAsync(_host, $"{_port}");
await Task.Run(async () =>
{
_client = new StreamSocket();
await _client.ConnectAsync(_host, $"{_port}");
int command = 1;
byte[] cmd = BitConverter.GetBytes(command);
byte[] path = Encoding.UTF8.GetBytes(@"C:\Users\Dave\Music\Offaiah-Trouble_(Club_Mix).mp3");
byte[] length = BitConverter.GetBytes(path.Length);
byte[] result = cmd.Concat(length.Concat(path)).ToArray();
await _client.OutputStream.WriteAsync(result.AsBuffer());
});
}
private async Task Receive()
{
while (true)
{
IBuffer inbuffer = new Windows.Storage.Streams.Buffer(4);
await _socket.InputStream.ReadAsync(inbuffer, 4, InputStreamOptions.None);
int command = BitConverter.ToInt32(inbuffer.ToArray(), 0);
//The inbuffer at this point contains: "\u0001\0\0\0", and the BitConverter resolves this to 1
inbuffer = new Windows.Storage.Streams.Buffer(4);
await _socket.InputStream.ReadAsync(inbuffer, 4, InputStreamOptions.None);
int length = BitConverter.ToInt32(inbuffer.ToArray(), 0);
//The inbuffer now contains: "2\0\0\0", and the BitConverter resolves this to "50"
inbuffer = new Windows.Storage.Streams.Buffer((uint)length);
await _socket.InputStream.ReadAsync(inbuffer, (uint)length, InputStreamOptions.Partial);
string path = Encoding.UTF8.GetString(inbuffer.ToArray());
}
}
}
如果您创建一个新的空白通用项目并运行它,您将看到它产生了正确的输出。
最终我发现我在这个流阅读器和另一个阅读器之间存在竞争条件。在主项目中,我不会一口气读取所有字节。我有一个单独的方法读取和解析“命令”,然后将控制权传递给另一种方法,以将控制权重定向到几个工作方法中的一个来服务该特定命令 - 剥离长度,然后剥离其余的有效负载。
问题是“命令阅读器”在工作人员可以读取其有效负载之前从流中读取另外 4 个字节。
显然答案是它应该在这里暂停并等待工作人员完成,但我一直在使用异步和等待,所以让我感到惊讶的是我遇到了这个问题。原因是缺少等待,以及可怕的异步无效,如下所示..
违规代码:
private async Task Listen()
{
while (true)
{
//expects a 4 byte packet representing a command
Debug.WriteLine($"Listening for socket command...");
IBuffer inbuffer = new Windows.Storage.Streams.Buffer(4);
await _socket.InputStream.ReadAsync(inbuffer, 4, InputStreamOptions.None);
int command = BitConverter.ToInt32(inbuffer.ToArray(), 0);
Debug.WriteLine($"Command received: {command}");
ParseCommand(command);
}
}
private async void ParseCommand(int command)
{
//...
}
...以及修改后的版本:
private async Task Listen()
{
while (true)
{
//expects a 4 byte packet representing a command
Debug.WriteLine($"Listening for socket command...");
IBuffer inbuffer = new Windows.Storage.Streams.Buffer(4);
await _socket.InputStream.ReadAsync(inbuffer, 4, InputStreamOptions.None);
int command = BitConverter.ToInt32(inbuffer.ToArray(), 0);
Debug.WriteLine($"Command received: {command}");
await ParseCommand(command);
}
}
private async Task ParseCommand(int command)
{
//...
}