如何使用StreamSocket广播消息

时间:2014-09-03 04:42:29

标签: c# windows-phone-8 stream-socket-client

我按照教程创建了通过Stream Socket连接的WindowsPhone设备。

向彼此发送消息的效果非常好。 但我不知道如何广播消息。有人能告诉我怎么样?

    private StreamSocket _socket = new StreamSocket();
    private StreamSocketListener _listener = new StreamSocketListener();
    private List<StreamSocket> _connections = new List<StreamSocket>();
    private bool _connecting = false;

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        //myConnectionTargetText.Text = "192.168.1.3";
        myConnectionTargetText.Text = "localhost"; // a TextBox
    }

    async private void WaitForData(StreamSocket socket)
    {
        var dr = new DataReader(socket.InputStream);
        //dr.InputStreamOptions = InputStreamOptions.Partial;
        var stringHeader = await dr.LoadAsync(4);

        if (stringHeader == 0)
        {
            LogMessage(string.Format("Disconnected (from {0})", socket.Information.RemoteHostName.DisplayName));
            return;
        }

        int strLength = dr.ReadInt32();

        uint numStrBytes = await dr.LoadAsync((uint)strLength);
        string msg = dr.ReadString(numStrBytes);

        LogMessage(string.Format("Received (from {0}): {1}", socket.Information.RemoteHostName.DisplayName, msg));

        WaitForData(socket);
    }

    async private void Connect(object sender, RoutedEventArgs e)
    {
        try
        {
            _connecting = true;
            await _socket.ConnectAsync(new HostName(myConnectionTargetText.Text), "3011");
            _connecting = false;

            LogMessage(string.Format("Connected to {0}", _socket.Information.RemoteHostName.DisplayName));

            WaitForData(_socket);
        }
        catch (Exception ex)
        {
            _connecting = false;
        }
    }

    async private void Listen(object sender, RoutedEventArgs e)
    {
        _listener.ConnectionReceived += listenerConnectionReceived;
        await _listener.BindServiceNameAsync("3011");

        LogMessage(string.Format("listening on {0}...", _listener.Information.LocalPort));
    }

    void listenerConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
    {
        _connections.Add(args.Socket);

        LogMessage(string.Format("Incoming connection from {0}", args.Socket.Information.RemoteHostName.DisplayName));

        WaitForData(args.Socket);
    }

    private void LogMessage(string message)
    {
        Dispatcher.BeginInvoke(() =>
            {
                myText.Text += message + Environment.NewLine;
            });
    }

    async private void SendMessage(StreamSocket socket, string message)
    {
        var writer = new DataWriter(socket.OutputStream);
        var len = writer.MeasureString(message); // Gets the UTF-8 string length.
        writer.WriteInt32((int)len);
        writer.WriteString(message);
        var ret = await writer.StoreAsync();
        writer.DetachStream();

        LogMessage(string.Format("Sent (to {0}) {1}", socket.Information.RemoteHostName.DisplayName, message)); // richTextBox
    }

1 个答案:

答案 0 :(得分:1)

无法通过流套接字进行多播,因为流套接字是端点到端点的连接。

您有两种选择:

  1. 让所有客户端连接到中央服务器,中央服务器会适当地调度消息。服务器将具有所有客户端的列表,因此它可以通过复制消息来模拟多播。
  2. 切换到UDP而不是TCP(即DatagramSocket)并使用多播。
  3. 请注意,切换到UDP会带来一系列问题:丢失可靠性(数据包可能会丢失),排序(数据包可能无序到达),以及最大数据报大小(您可以“#dd; d必须自己拆分你的消息)。出于这个原因,大多数应用程序使用中央服务器伪造多播。