阻塞监听防止断开连接
Posted
技术标签:
【中文标题】阻塞监听防止断开连接【英文标题】:blocking listen prevents disconnect 【发布时间】:2015-05-01 16:07:17 【问题描述】:问题概述:
我需要连接到 IRC 服务器。连接后,程序将向通道发送消息,并且将通过多行返回响应。我需要阅读这些行并将其存储在一个变量中以供以后使用。消息末尾的特殊字符 (]) 将定义多行消息的结尾。一旦我们收到此字符,IRC 会话应该断开连接并继续处理。
情况:
我正在使用 Smartirc4net 库。调用 irc.Disconnect() 大约需要 40 秒来断开会话。一旦我们收到 ] 字符,会话应该断开,Listen() 不应该阻塞,程序的其余部分应该继续运行。
研究:
我发现了这个:smartirc4net listens forever, can't exit thread,我认为这可能是同一个问题,但是,我不确定我需要做些什么来解决这个问题。
代码:
public class IrcCommunicator
public IrcClient irc = new IrcClient();
string data;
public string Data get return data;
// this method we will use to analyse queries (also known as private messages)
public void OnQueryMessage(object sender, IrcEventArgs e)
data += e.Data.Message;
if (e.Data.Message.Contains("]"))
irc.Disconnect(); //THIS TAKES 40 SECONDS!!!
public void RunCommand()
irc.OnQueryMessage += new IrcEventHandler(OnQueryMessage);
string[] serverlist;
serverlist = new string[] "127.0.0.1" ;
int port = 6667;
string channel = "#test";
try
irc.Connect(serverlist, port);
catch (ConnectionException e)
// something went wrong, the reason will be shown
System.Console.WriteLine("couldn't connect! Reason: " + e.Message);
try
// here we logon and register our nickname and so on
irc.Login("test", "test");
// join the channel
irc.RfcJoin(channel);
irc.SendMessage(SendType.Message, "test", "!query");
// here we tell the IRC API to go into a receive mode, all events
// will be triggered by _this_ thread (main thread in this case)
// Listen() blocks by default, you can also use ListenOnce() if you
// need that does one IRC operation and then returns, so you need then
// an own loop
irc.Listen();
// when Listen() returns our IRC session is over, to be sure we call
// disconnect manually
irc.Disconnect();
catch (Exception e)
// this should not happen by just in case we handle it nicely
System.Console.WriteLine("Error occurred! Message: " + e.Message);
System.Console.WriteLine("Exception: " + e.StackTrace);
IrcBot bot = new IrcBot();
bot.RunCommand();
ViewBag.IRC = bot.Data;
如您所见,一旦这 感谢您花时间查看此代码并阅读我的问题描述。如果您有任何想法或其他建议,请告诉我。
迈克
【问题讨论】:
【参考方案1】:在 irc.Disconnect() 之前,通过在 OnQueryMessage() 中调用 RfcQuit(),我能够立即成功断开连接;
【讨论】:
以上是关于阻塞监听防止断开连接的主要内容,如果未能解决你的问题,请参考以下文章
Strophe javascript 防止在某些延迟时断开连接