• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 5. Managing Streams > A Simple Publisher/Subscriber Example

5.1. A Simple Publisher/Subscriber Example

Example 5-1 is a somewhat oversimplified but complete example script that shows the essential steps in publishing one live stream and subscribing to a second live stream. The example shows how video, audio, and ActionScript data can be sent via a published stream and received by subscribing to another stream.

Example 5-1. A very basic two-way messaging client

// writeln(  ) replaces trace(  ) and writes messages into the trace_txt field.
function writeln (msg) {
  trace_txt.text += msg + "\n";
  trace_txt.scroll = trace_txt.maxscroll;
}

// onStatus( ) sets up the streams and buttons when a connection is
// established or lost.
NetConnection.prototype.onStatus = function (info) {
  writeln("Level: " + info.level + ", code: " + info.code);
  if (info.code == "NetConnection.Connect.Success") {
    out_ns = new NetStream(this);
    out_ns.attachAudio(Microphone.get( ));
    out_ns.attachVideo(Camera.get( ));
    in_ns = new NetStream(this);
    in_ns.showMessage = function (msg) {
      writeln(msg);
    };
    // remote_video is the instance name of an embedded video object.
    remote_video.attachVideo(in_ns);
    in_ns.play("public/" + remoteUserName);
    connect_pb.setLabel("Disconnect");
    send_pb.setEnabled(true);
  }
  else if (!this.isConnected) {
    if (out_ns) out_ns.close( );
    if (in_ns) in_ns.close( );
    connect_pb.setLabel("Connect");
    send_pb.setEnabled(false);
  }
};

NetStream.prototype.onStatus = function (info) {
  for (var p in info) {
    writeln("info." + p + ": " + info[p]);
  }
};

// doSend( ) is called when the send_pb is clicked.
function doSend (msg) {
  out_ns.send("showMessage", input_txt.text);
  input_txt.text = "";
}

/* doConnect( ) is called when the connect_pb is clicked.
 * It stores the text in the userName_txt and remoteUserName_txt
 * fields in global variables for later use if a connection is
 * attempted. See the onStatus( ) method.
 */
function doConnect (pb) {
  if (pb.getLabel( ) == "Connect") {
    userName = userName_txt.text;
    remoteUserName = remoteUserName_txt.text;
    nc.connect("rtmp:/courseChat/algebra101", userName);
  }
  else {
    nc.close( );
  }
}

function doSendStream (pb) {
  if (pb.getLabel( ) == "Send Stream" && nc.isConnected) {
    pb.setLabel("Stop Stream");
    out_ns.publish("public/" + userName);
  }
  else {
    pb.setLabel("Send Stream");
    out_ns.publish(false);
  }
}

send_pb.setEnabled(false);
nc = new NetConnection( );

					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint