为什么我的Universal App StreamSocket附加3个空字符?

时间:2015-11-02 15:26:29

标签: c# sockets stream win-universal-app

我正在为SocketStream设置我的通用应用程序,但我的服务器在第一次传输时收到3个空字符。并且它在其他所有内容上附加3个空字符。这是我的代码:

    /// <summary>
    /// This is the click handler for the 'ConnectSocket' button.
    /// </summary>
    /// <param name="sender">Object for which the event was generated.</param>
    /// <param name="e">Event's parameters.</param>
    private async void ConnectSocket_Click(object sender, RoutedEventArgs e)
    {

        // By default 'HostNameForConnect' is disabled and host name validation is not required. When enabling the
        // text box validating the host name is required since it was received from an untrusted source
        // (user input). The host name is validated by catching ArgumentExceptions thrown by the HostName
        // constructor for invalid input.
        try
        {
            hostName = new HostName(HostNameForConnect.Text);
        }
        catch (ArgumentException)
        {
            return;
        }

        StreamSocket socket = new StreamSocket();

        // If necessary, tweak the socket's control options before carrying out the connect operation.
        // Refer to the StreamSocketControl class' MSDN documentation for the full list of control options.
        socket.Control.KeepAlive = false;

        // Save the socket, so subsequent steps can use it.
        CoreApplication.Properties.Add("clientSocket", socket);
        try
        {

            await socket.ConnectAsync(hostName, ServiceNameForConnect.Text);

            // Mark the socket as connected. Set the value to null, as we care only about the fact that the 
            // property is set.
            CoreApplication.Properties.Add("connected", null);

            //Do some basic conversations
            DataWriter dw = new DataWriter(socket.OutputStream);
            DataReader dr = new DataReader(socket.InputStream);
            dr.InputStreamOptions = InputStreamOptions.Partial;
            await dr.LoadAsync(250);
            Response.Text=("Response: " + dr.ReadString(dr.UnconsumedBufferLength)+Environment.NewLine);
            await Task.Delay(TimeSpan.FromSeconds(1));
            Response.Text+="Sending USER Guest"+Environment.NewLine;
            dw.WriteUInt32(dw.MeasureString("USER Guest"));
            dw.WriteString("USER Guest");
            await dw.StoreAsync();
            await dw.FlushAsync();
            await Task.Delay(TimeSpan.FromSeconds(1));
            await dr.LoadAsync(250);
            Response.Text+="Response: " + dr.ReadString(dr.UnconsumedBufferLength)+Environment.NewLine;
            await Task.Delay(TimeSpan.FromSeconds(1));
            Response.Text += "Sending PASS " + Environment.NewLine;
            dw.WriteUInt32(dw.MeasureString("PASS "));
            dw.WriteString("PASS ");
            await dw.StoreAsync();
            await dw.FlushAsync();
            await Task.Delay(TimeSpan.FromSeconds(1));
            await dr.LoadAsync(250);
            Response.Text += "Response: " + dr.ReadString(dr.UnconsumedBufferLength) + Environment.NewLine;
            await Task.Delay(TimeSpan.FromSeconds(1));
            Response.Text += "Sending PWD" + Environment.NewLine;
            dw.WriteUInt32(dw.MeasureString("PWD"));
            dw.WriteString("PWD");
            await dw.StoreAsync();
            await dw.FlushAsync();
            await Task.Delay(TimeSpan.FromSeconds(1));
            await dr.LoadAsync(250);
            Response.Text += "Response: " + dr.ReadString(dr.UnconsumedBufferLength) + Environment.NewLine;
        }
        catch (Exception exception)
        {
            // If this is an unknown status it means that the error is fatal and retry will likely fail.
            if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
            {

            }
        }
    }

我的服务器收到“\ 0 \ 0 \ 0”。我永远不会发送空白消息或空字符。我不明白。

有趣的是,如果我第二次发送USER Guest:

            Response.Text+="Sending USER Guest"+Environment.NewLine;
            dw.WriteUInt32(dw.MeasureString("USER Guest"));
            dw.WriteString("USER Guest");
            await dw.StoreAsync();
            await dw.FlushAsync();
            await Task.Delay(TimeSpan.FromSeconds(1));
            await dr.LoadAsync(250);
            Response.Text+="Response: " + dr.ReadString(dr.UnconsumedBufferLength)+Environment.NewLine;
            await Task.Delay(TimeSpan.FromSeconds(1));
            Response.Text += "Sending USER Guest" + Environment.NewLine;
            dw.WriteUInt32(dw.MeasureString("USER Guest"));
            dw.WriteString("USER Guest");
            await dw.StoreAsync();
            await dw.FlushAsync();
            await Task.Delay(TimeSpan.FromSeconds(1));
            await dr.LoadAsync(250);
            Response.Text += "Response: " + dr.ReadString(dr.UnconsumedBufferLength) + Environment.NewLine;
            await Task.Delay(TimeSpan.FromSeconds(1));

服务器收到“\ 0 \ 0 \ 0”那么“USER Guest \ 0 \ 0 \ 0”。所以有两个问题:

为什么它会附加3个空字符,为什么第一个消息是空白的?

更新:我知道它不是服务器,因为我将服务器与另一个c#控制台应用程序一起使用。比较代码是:

                Console.WriteLine("Sending Username Command");
                sw.WriteLine("USER Guest");
                sw.Flush();
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine("Response: " + sr.ReadLine());
                Console.WriteLine("Sending Password Command");
                sw.WriteLine("PASS ");
                sw.Flush();
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine("Response: " + sr.ReadLine());
                Console.WriteLine("Sending PWD command");
                sw.WriteLine("PWD");
                sw.Flush();

sw是节选者。这里服务器收到“USER Guest”

2 个答案:

答案 0 :(得分:2)

停止这样做:

dw.WriteUInt32(dw.MeasureString("USER Guest"));
dw.WriteString("USER Guest");

然后开始这样做:

dw.WriteString("USER Guest\n");

目前,您正在发送一个长度值,作为发送为4个字节的uint,然后发送一个字符串。碰巧,你发送的字符串的长度恰好是10个字节长。所以你要发送的前4个字节是0,0,0,10。实际上,字符代码10与\n相同,因此它读作完整的文本行 - 相同作为您的控制台应用程序(显然可行),您可以通过调用WriteLine

答案 1 :(得分:0)

由于我使用了

,因此添加了空字符
dw.WriteUInt32(dw.MeasureString("USER Guest"));

因为我的文本只需要1个字节,所以其他3个字节被3个空字符占用。我把它改成了

dw.WriteByte((byte)dw.MeasureString("USER Guest"));

现在我附加了0个空字符。我仍然有一个问题,因为第一次通信只是一个空字符串而不是3个空字符。