0

我按照教程创建通过 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
    }
4

1 回答 1

1

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

你有两个选择:

  1. 让所有客户端连接到中央服务器,该服务器会适当地分派消息。服务器将拥有所有客户端的列表,因此它可以通过复制消息来模拟多播。
  2. 切换到 UDP 而不是 TCP(即DatagramSocket)并使用多播。

请注意,切换到 UDP 会带来一系列问题:您会失去可靠性(数据包可能会丢失)、排序(数据包可能会乱序到达),并且存在最大数据报大小(您必须自己拆分消息) . 出于这个原因,大多数应用程序通过使用中央服务器来伪造多播。

于 2014-09-03T11:58:01.653 回答