libnice解讀
Overview
libnice是解決p2p問題的庫,兼容多種協(xié)議译柏。本文主要在janus服務(wù)器與webrtc通信的環(huán)境下的解讀。libnice基于glib開發(fā)唆垃,所以最好先了解glib
simple-example
// loop有點(diǎn)類似ios中的runloop
gloop = g_main_loop_new(NULL, FALSE);
io_stdin = g_io_channel_unix_new(fileno(stdin));
// Create the nice agent
agent = nice_agent_new(g_main_loop_get_context (gloop),
NICE_COMPATIBILITY_RFC5245);
if (agent == NULL)
g_error("Failed to create agent");
// Set the STUN settings and controlling mode
if (stun_addr) {
g_object_set(agent, "stun-server", stun_addr, NULL);
g_object_set(agent, "stun-server-port", stun_port, NULL);
}
g_object_set(agent, "controlling-mode", controlling, NULL);
// Connect to the signals
g_signal_connect(agent, "candidate-gathering-done",
G_CALLBACK(cb_candidate_gathering_done), NULL);
g_signal_connect(agent, "new-selected-pair",
G_CALLBACK(cb_new_selected_pair), NULL);
g_signal_connect(agent, "component-state-changed",
G_CALLBACK(cb_component_state_changed), NULL);
g_signal_connect (agent, "new-selected-pair-full",G_CALLBACK (janus_ice_cb_new_selected_pair), NULL);
// Create a new stream with one component,(其中component序號(hào)是從1開始)
stream_id = nice_agent_add_stream(agent, 1);
if (stream_id == 0)
g_error("Failed to add stream");
// Attach to the component to receive the data
// Without this call, candidates cannot be gathered
nice_agent_attach_recv(agent, stream_id, 1,
g_main_loop_get_context (gloop), cb_nice_recv, NULL);
// Start gathering local candidates
if (!nice_agent_gather_candidates(agent, stream_id))
g_error("Failed to start candidate gathering");
g_debug("waiting for candidate-gathering-done signal...");
// Run the mainloop. Everything else will happen asynchronously
// when the candidates are done gathering.
g_main_loop_run (gloop);
g_main_loop_unref(gloop);
g_object_unref(agent);
g_io_channel_unref (io_stdin);
也可以自己直接通過glib接口直接創(chuàng)建更加詳細(xì)的agent:
handle->agent = g_object_new(NICE_TYPE_AGENT, "compatibility", NICE_COMPATIBILITY_DRAFT19, "main-context", icectx, "reliable", FALSE, "full-mode", TRUE, "ice-udp", TRUE, "ice-tcp", FALSE, NULL);
reliable表示是否可靠傳輸接校,一般用false,UDP穿墻成功率更高糖耸,full-mode就是表示是否不是lite模式秘遏,所以false表示是liteice模式。