我正在创建一个Win 8商店应用程序,其中使用StreamSocket连接到用Java编写的服务器。当我在调试中运行应用程序时,在StreamSocket.ConnectAsync(...),DataWriter.StoreAsync()和DataReader.LoadAsync(...)上具有断点,它将连接,发送消息并接收回消息。但是,一旦我删除了任何一个断点,该方法就不会起作用。如何解决此问题?这是我的代码:

public async void Connect()
{
    try
    {
        await socket.ConnectAsync(new Windows.Networking.HostName(ip),
            "50000", SocketProtectionLevel.PlainSocket);
        Connected = true;
    }
    catch (Exception e)
    {
        if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
        {
            throw;
        }

        Windows.UI.Popups.MessageDialog md =
            new Windows.UI.Popups.MessageDialog("Error: " + e.Message);
        return;
    }
    return;

}

public async void HandShake()
{
    try
    {

        //output
        writer = new DataWriter(socket.OutputStream);
        writer.UnicodeEncoding =
             Windows.Storage.Streams.UnicodeEncoding.Utf8;

        byte[] nameBytes = Encoding.UTF8.GetBytes(Name.ToCharArray());
        writer.WriteBytes(nameBytes);
        await writer.StoreAsync();

        await writer.FlushAsync();
        writer.DetachStream();
        writer.Dispose();


        //input
        reader = new DataReader(socket.InputStream);
        reader.InputStreamOptions = InputStreamOptions.Partial;
        reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

        uint bytesAvailable = await reader.LoadAsync(4096);
        byte[] byArray = new byte[bytesAvailable];
        reader.ReadBytes(byArray);
        string temp = Encoding.UTF8.GetString(byArray, 0,
            Convert.ToInt32(bytesAvailable));

        temp = temp.Substring(0, temp.Length - 1);

        if (temp == "NAME OK")
        {
            GoodName = true;
        }

        reader.DetachStream();
        reader.Dispose();
    }
    catch (Exception e)
    {
        //await Task.WhenAll(tasks.ToArray());
        if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
        {
            throw;
        }

        Windows.UI.Popups.MessageDialog md =
            new Windows.UI.Popups.MessageDialog("Error: " + e.Message);
        md.ShowAsync();
    }
}

最佳答案

默认情况下,LoadAsync不会阻塞,直到所有请求的字节都已被读取。您可能会收到部分消息。

正如我在博客中所描述的,您将需要实现协议(protocol)使用的message framing类型。

P.S.避免使用async void。这确实使您的错误处理复杂化。

10-02 16:37