libnice解读
Overview
libnice是解决p2p问题的库,兼容多种协议。本文主要在janus服务器与webrtc通信的环境下的解读。libnice基于glib开发,所以最好先了解glib
simple-example
// loop有点类似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序号是从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接口直接创建更加详细的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模式。
网友评论