StreamSocketListener接收多条消息

时间:2018-09-30 11:57:10

标签: c# sockets uwp listener

这是我的代码,您能帮我更改代码,以便接收多条消息吗?目前,我只能回答一个问题,然后客户端必须重新连接。

希望你能帮助我。

public string PortNumber = "1337";

public MainPage()
{
    this.InitializeComponent();
    StartServer();
}

private async void StartServer()
{
    try
    {
        var streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();

        // The ConnectionReceived event is raised when connections are received.
        streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;

        // Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
        await streamSocketListener.BindServiceNameAsync(this.PortNumber);

        this.serverListBox.Items.Add("server is listening...");
    }
    catch (Exception ex)
    {
        Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
        this.serverListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
    }
}

private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
{
    string request;
    using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
    {
        request = await streamReader.ReadLineAsync();
    }

    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.TB1.Text=(string.Format("server received the request: \"{0}\"", request)));

    // Echo the request back as the response.
    using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
    {
        using (var streamWriter = new StreamWriter(outputStream))
        {
            await streamWriter.WriteLineAsync(request);
            await streamWriter.FlushAsync();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您应该始终收听StreamSocketListener.ConnectionReceived Event中即将出现的消息,该事件仅在StreamSocketListener对象上收到连接时才会触发。如果要始终接收发送的数据,则应始终在StreamSocketListener.ConnectionReceived Event中进行读取。

这是官方StreamSocket中的示例代码:

Scenario1_Start.xaml.cs中,OnConnection与您的StreamSocketListener_ConnectionReceived方法相同。您还可以从官方示例中了解更多信息。

private async void OnConnection(
    StreamSocketListener sender, 
    StreamSocketListenerConnectionReceivedEventArgs args)
{
    DataReader reader = new DataReader(args.Socket.InputStream);
    try
    {
        while (true)
        {
            // Read first 4 bytes (length of the subsequent string).
            uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
            if (sizeFieldCount != sizeof(uint))
            {
                // The underlying socket was closed before we were able to read the whole data.
                return;
            }

            // Read the string.
            uint stringLength = reader.ReadUInt32();
            uint actualStringLength = await reader.LoadAsync(stringLength);
            if (stringLength != actualStringLength)
            {
                // The underlying socket was closed before we were able to read the whole data.
                return;
            }

            // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal
            // the text back to the UI thread.
            NotifyUserFromAsyncThread(
                String.Format("Received data: \"{0}\"", reader.ReadString(actualStringLength)), 
                NotifyType.StatusMessage);
        }
    }
    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)
        {
            throw;
        }

        NotifyUserFromAsyncThread(
            "Read stream failed with error: " + exception.Message, 
            NotifyType.ErrorMessage);
    }
}