2020-10-27 07:01:21 阅读次数: 0
libnice介绍:
libnice库是基于ICE协议实现的一套通信连接库。
主要功能是实现p2p连接及媒体数据流发送接收。其类似于webrtc源码中自带的libjingo。我们可在我们的项目中使用libnice库来实现端到端的ICE连接和数据流发送接收。以及candidates(候选地址)和SDP(媒体描述文件)的相互交换。
libnice库是基于glibc语言的,跨平台,在linux和手机端都可使用,但需依赖于glib库。
libnice常用函数调用流程:
#include <agent.h>
guint stream_id;
gchar buffer[] = "hello world!";
gchar *ufrag = NULL, *pwd = NULL;
gchar *remote_ufrag, *remote_pwd;
GSList *lcands = NULL;
// Create a nice agent, passing in the global default GMainContext.
NiceAgent *agent = nice_agent_new (NULL, NICE_COMPATIBILITY_RFC5245);
spawn_thread_to_run_main_loop (g_main_loop_new (NULL, FALSE));
// Connect the signals
g_signal_connect (G_OBJECT (agent), "candidate-gathering-done",
G_CALLBACK (cb_candidate_gathering_done), NULL);
g_signal_connect (G_OBJECT (agent), "component-state-changed",
G_CALLBACK (cb_component_state_changed), NULL);
g_signal_connect (G_OBJECT (agent), "new-selected-pair",
G_CALLBACK (cb_new_selected_pair), NULL);
// Create a new stream with one component and start gathering candidates
stream_id = nice_agent_add_stream (agent, 1);
nice_agent_gather_candidates (agent, stream_id);
// Attach I/O callback the component to ensure that:
// 1) agent gets its STUN packets (not delivered to cb_nice_recv)
// 2) you get your own data
nice_agent_attach_recv (agent, stream_id, 1, NULL,
cb_nice_recv, NULL);
// ... Wait until the signal candidate-gathering-done is fired ...
lcands = nice_agent_get_local_candidates(agent, stream_id, 1);
nice_agent_get_local_credentials(agent, stream_id, &ufrag, &pwd);
// ... Send local candidates and credentials to the peer
// Set the peer's remote credentials and remote candidates
nice_agent_set_remote_credentials (agent, stream_id, remote_ufrag, remote_pwd);
nice_agent_set_remote_candidates (agent, stream_id, 1, rcands);
// ... Wait until the signal new-selected-pair is fired ...
// Send our message!
nice_agent_send (agent, stream_id, 1, sizeof(buffer), buffer);
// Anything received will be received through the cb_nice_recv callback.
// You must be running a GMainLoop on the global default GMainContext in
// another thread for this to work.
// Destroy the object
g_object_unref(agent);
libnice官方资料:https://libnice.freedesktop.org/libnice/NiceAgent.html