个人资料

跳过导航链接首页 > 博客列表 > 博客正文

SignalR教程18-.Net客户端设置连接

分类:

设置WPF客户端的最大并发连接数

在WPF客户端中,可能必须将并发连接的最大数量从默认值2增加.建议值为10.

var hubConnection = new HubConnection("http://www.contoso.com/");
IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
ServicePointManager.DefaultConnectionLimit = 10;
await hubConnection.Start();

连接时指定query参数

如果要在客户端连接时将数据发送到服务器,则可以将query字符串参数添加到连接对象。 以下示例显示如何在客户端代码中设置query参数。

//客户端上
var querystringData = new Dictionary<string, string>();
querystringData.Add("contosochatversion", "1.0");
var connection = new HubConnection("http://contoso.com/", querystringData);
//服务器上
public class StockTickerHub : Hub
{
    public override Task OnConnected()
    {
        var version = Context.QueryString["contosochatversion"];
        if (version != "1.0")
        {
            Clients.Caller.notifyWrongVersion();
        }
        return base.OnConnected();
    }
}

指定连接方式

signal具有自动选择可用的连接传输方法功能,如果连接时直接指定传输方法,请使用下面的代码:

var hubConnection = new HubConnection("http://www.contoso.com/");
IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
await hubConnection.Start(new LongPollingTransport());

可用的连接方法字段:

LongPollingTransport

ServerSentEventsTransport

WebSocketTransport

AutoTransport

其他配置

//指定http抬头
hubConnection = new hubConnection("http://www.contoso.com/");
connection.Headers.Add("headername", "headervalue");
IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
await connection.Start();
//使用客户端证书验证
hubConnection = new hubConnection("http://www.contoso.com/");
hubConnection.AddClientCertificate(X509Certificate.CreateFromCertFile("MyCert.cer"));
IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
await connection.Start();

(the End)

songshizhao
最初发表2017/11/20 22:13:40 最近更新2017/11/20 22:13:40 2981
为此篇作品打分
10
   评论