【问题标题】:Streaming live tweets to the my .net website将实时推文流式传输到我的 .net 网站
【发布时间】:2015-06-25 22:48:51
【问题描述】:

我正在开发一个基于 Web 的应用程序,我想在其中显示特定查询的 Twitter 流。用户确实需要刷新网页视图,它会自动加载推文。

到目前为止,我已经使用 tweetinvi 创建了一个简单的控制台应用程序,它读取推文并在推文上执行所有自定义逻辑。

接下来我需要知道如何创建项目布局/基础设施,以便我的 Web 应用程序无需客户端交互即可获得持续的提要。

【问题讨论】:

    标签: c# asp.net-web-api stream tweetinvi


    【解决方案1】:

    正如 Nathan Cooper 所说,SignalR 是实现这一目标的最佳方式。正如我实际上只是构建了您所描述的内容,我将为您详细介绍您需要做的事情..

    创建一个新的 ASP.NET MVC 项目,并使用 NuGet 和 Tweetinvi 安装 ASP.NET SignalR

    右键单击 App_Start 文件夹并添加一个新的 OWIN Startup 类(如果您使用 NuGet 安装了 SignalR,则该类应列在上下文菜单中)。

    您的 OWIN 启动类应如下所示:

    [assembly: OwinStartup(typeof(TwitterClient.Web.App_Start.Startup))]
    
    namespace TwitterClient.Web.App_Start
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {            
                app.MapSignalR();
            }
        }
    }
    

    向项目中添加一个名为“Hubs”的新文件夹并添加一个新的 SignalR Hub 类(这也应该在 Visual Studio 的新文件对话框中作为模板提供)。

    在项目中的任何位置创建一个名为“TwitterConnection”的新类。在此类的构造函数中,执行您在控制台应用程序中执行的所有操作,以使用 Tweetinvi 连接到 Twitter API。通常,当您在 SignalR 中将数据从服务器广播到客户端时,您可以在 Hub 类中执行此操作,但您可以使用 GlobalHost.ConnectionManager.GetHubContext<HUBNAME>(); 在 Hub 类本身之外获取对 SignalR 集线器的引用,其中 HUBNAME 是集线器的名称.所以你的TwitterConnection 类应该是这样的:

    public class TwitterConnection {
            private string _consumerKey = ConfigurationManager.AppSettings.Get("consumerKey");
            private string _consumerSecret = ConfigurationManager.AppSettings.Get("consumerSecret");
            private string _accessKey = ConfigurationManager.AppSettings.Get("accessToken");
            private string _accessToken = ConfigurationManager.AppSettings.Get("accessTokenSecret");
    
            private IHubContext _context = GlobalHost.ConnectionManager.GetHubContext<TwitterHub>();
    
            public TwitterConnection()
            {
                // Access the filtered stream
                var filteredStream = Stream.CreateFilteredStream();
    
                filteredStream.MatchingTweetReceived += (sender, args) => 
                { 
                    _context.Clients.All.broadcast(args.Tweet.Text);
                };
    
                filteredStream.StartStreamMatchingAllConditions();
    
            }
    }
    

    就服务器端而言,您需要找到一种方法来确保在任何时候只有一个流实例向 Twitter 开放。我快速而肮脏的做法是使用Task.Factory.StartNew 创建一个新任务来管理Global.asax 文件中的流:

    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
    
                // Start a new instance of the TwitterConnection class
                Task.Factory.StartNew(() => new TwitterConnection());
            }
    

    最后,您需要连接 SignalR 的客户端元素。在您的 MVC 布局视图(即 Views/Shared/_Layout.cshtml)中,在 HTML 标记的底部添加对 SignalR JavaScript 库、生成的 Hub 代理和您的样板 SignalR JavaScript 所在的外部 JavaScript 文件的引用:

    <!--Reference the SignalR library. -->
    <script src="../../Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <script src="../../Scripts/application.js"></script>
    

    最后,您在application.js(或任何您想调用的名称)中的样板代码将如下所示:

    // document ready shorthand
    $(function () {
        // obtain reference to the hub proxy and hub itself
        var theHub = $.connection.twitterHub;
    
    
        // this is the function that the server will call to broadcast new tweets
        theHub.client.broadcast = function (tweet) {
            var item = '<li>' + tweet.text + '</li>';
            $('ul.tweets').prepend(item);
        };
    
        // this is a function that indicates that connection to the hub has been successful
        $.connection.hub.start().done(function () {
            console.log("connected");
        });
    });
    

    您的Index.cshtml 文件中只会有一个空的&lt;ul&gt;,新推文将在收到时添加到其中:

    @{
        ViewBag.Title = "Home Page";
    }
    
    <div class="row">
        <div class="col-md-12">
            <ul class="tweets"></ul>
        </div>
    </div>
    

    【讨论】:

      【解决方案2】:

      您需要将实时数据推送到浏览器。使用SignalR

      SignalR 是一个很棒的 ASP.NET 库,可让您编写实时 Web 应用程序。它在幕后使用Websockets,但为旧版浏览器提供了许多后备位置。 tutorial link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-28
        • 1970-01-01
        • 1970-01-01
        • 2017-10-09
        • 2013-09-03
        • 1970-01-01
        • 1970-01-01
        • 2014-03-21
        相关资源
        最近更新 更多