1
我需要你的幫助。GMainLoop和TCP監聽線程
我有附帶超時回調主迴路GMainLoop:
MainLoop = g_main_loop_new(NULL, FALSE);
g_timeout_add_seconds(Interval, TimeoutCallback, (gpointer) Rec);
g_main_loop_run(MainLoop);
而且監聽套接字:
int ControlServer::GStart()
{
int listenfd;
GIOChannel *in;
socklen_t addr_len;
listenfd = TcpListen(host, port, &addr_len);
in = g_io_channel_unix_new(listenfd);
g_io_add_watch(in, G_IO_IN, (GIOFunc) Handler, (gpointer) Rec);
g_io_channel_unref(in);
return 0;
}
所有的好和超時功能正常工作,直到任何客戶端沒有連接聽取插座。連接後,超時不能在客戶端連接的所有時間工作。我認爲它與線程相關,就像GLib文檔默認的GMainContext在一個線程中執行的所有動作一樣。我修改這個代碼:
int ControlServer::GThStart()
{
int listenfd;
socklen_t addr_len;
GIOChannel *Channel;
GSource *Source;
GMainContext *Context;
listenfd = TcpListen(host, port, &addr_len);
Channel = g_io_channel_unix_new(listenfd);
Source = g_io_create_watch(Channel, G_IO_IN);
g_source_set_callback(Source, (GSourceFunc) Handler, (gpointer) Rec, NULL);
Context = g_main_context_new();
g_source_attach(Source, Context);
g_source_unref(Source);
return 0;
}
但現在插座着,卻沒有任何客戶端可以連接到它和處理函數不會被調用。
處理程序代碼如下:
bool ControlServer::Handler(GIOChannel *in, GIOCondition condition, gpointer data)
{
Recorder *Rec = (Recorder *) data;
struct sockaddr_storage income;
int insock, newsock;
socklen_t income_len;
struct sockaddr peer;
socklen_t size;
Access *access;
insock = g_io_channel_unix_get_fd(in);
income_len = sizeof(income);
newsock = accept(insock, (struct sockaddr *) &income, &income_len);
size = sizeof(peer);
getpeername(newsock, &peer, &size);
struct sockaddr_in *ipv4 = (struct sockaddr_in *) &peer;
access = new Access(newsock, ipv4, MAXN);
access->Cycle(Rec);
delete access;
return true;
}
類「訪問」檢查客戶的權利和實現無限循環的執行協議處理交換,同時客戶端或服務器沒有密切的聯繫。
do
{
result = DoCycle(Rec);
sprintf(str, "DEBUG: DoCycle(Rec) returns '%d'\n", result);
AppendLog(str, class_name, DEBUG);
} while (result != -1);
只有當連接關閉或通過TCP錯誤交換數據時,DoCycle()才返回'-1'。
有什麼不對? 謝謝!
是什麼處理程序是什麼樣子? – nemequ
我剛剛添加Handler的代碼和一些解釋。 – Xuch