Twitter Streaming过滤器API:定期获取IOE异常

时间:2012-10-19 22:43:58

标签: c# twitter streaming

我正在使用twitter流API(C#)并定期获取IOE异常(每12小时或类似的东西),而Stream阅读器正在尝试读取JSON对象(readLine)。请查看异常&下面的代码。任何帮助将受到高度赞赏。提前谢谢。

  

无法从传输连接中读取数据:连接尝试失败,因为连接方在一段时间后没有正确响应或建立连接失败,因为连接的主机无法响应。

string userName = "XXXX";
string password = "XXXX";
string url = @"https://stream.twitter.com/1.1/statuses/filter.json";
string parameters = "follow=" + userIds  +"&track=" + keywords;

// Request and Response 
HttpWebRequest webRequest = null;
HttpWebResponse webResponse = null;
StreamReader streamReader = null;
byte[] byteArray;

// Establishing connection with twitter filter.json
byteArray = Encoding.UTF8.GetBytes(parameters);
webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Credentials = new NetworkCredential(userName, password);
webRequest.Timeout = 100000;

Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";

byte[] postData = encode.GetBytes(parameters);
webRequest.ContentLength = postData.Length;
Stream twitterPost = webRequest.GetRequestStream();
twitterPost.Write(postData, 0, postData.Length);
twitterPost.Close();

webResponse = (HttpWebResponse)webRequest.GetResponse();
streamReader = new StreamReader(webResponse.GetResponseStream(), encode);

Stopwatch sw = new Stopwatch();
sw.Start();

while (sw.Elapsed < TimeSpan.FromDays(365))
{
    String json = streamReader.ReadLine(); // [The program stop here. throws exception]
    if (json == "")
    {
     continue;
    }
    Packet dataPacket = new Packet() { json = json, id = id++ };
    ThreadPool.QueueUserWorkItem(new WaitCallback(Execute), dataPacket);
 }

// Aborting the request and closing the stream
webRequest.Abort();
sw.Stop();
streamReader.Close();
streamReader = null;
webResponse.Close();
webResponse = null;

1 个答案:

答案 0 :(得分:0)

听起来您的互联网连接中断或您与路由器的连接。

在我的国家,大多数ISP每天午夜刷新您的IP地址,这会导致连接丢失几秒钟,也许您的ISP正在做类似的事情?