SignalR是.net中一個不錯的推送架構。它包含長連接配接跟集線器兩種方式,我需要的是兩個項目之間的通訊,也就是A控制台項目,向B web項目發送資料,然後B就推送到各個使用者頁面。
下面的代碼是A控制台項目代碼
class getData
{
//日志輸出
private static ILog log = log4net.LogManager.GetLogger(typeof(getData));
//連接配接web
public static Connection connection =new Connection("http://localhost:4669/webConnections");
static getData() //靜态構造初始化長連接配接參數
{
//添加頭檔案,這樣B就知道是A傳輸資料而不是頁面用戶端,還可以使用connection.CookieContainer來區分
connection.Headers.Add("where", "windowserver");
try
{
connection.Received+=Console.WriteLine;//控制台輸出
connection.Start().Wait(); //wait()方法十分重要,要不然就異步執行後面的語句了
}
catch (System.Exception ex)
{
log.Error("無法連接配接web應用,Start方法不能使用" + ex.ToString());
throw ex;
}
}
public void QueryDataAndToWeb(object sta)
{
string datajson = connection.JsonSerializeObject(sta);//序列化成JSON傳送到web
try
{
connection.Send(datajson).Wait();
}
catch (System.Exception ex)
{
Console.Write(ex);
log.Error("無法連接配接web應用,Send方法不能使用" + ex.ToString());
}
}
}
在上述代碼中,我隻是簡單的寫出使用方法,一些異常處理,還沒處理完。
下面貼出B web項目
建立一個Startup.cs
[assembly: OwinStartup(typeof(Startup))]
namespace signalr
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 有關如何配置應用程式的詳細資訊,請通路 http://go.microsoft.com/fwlink/?LinkID=316888
// 配置上文實作的ChatConnections
app.MapSignalR<ChatConnection>("/webConnections");
}
}
}
ChatConnection類:
public class ChatConnection : PersistentConnection
{
private static string _WinServiceID = "";//為空字元串表示斷線,用于從内部觸發推送
protected override Task OnConnected(IRequest request, string connectionId)
{
string where = request.Headers.Get("where");
if (where !=null&&where.Equals("windowserver"))
_WinServiceID = connectionId;
return Connection.Send(connectionId, "welcome!");
}
protected override Task OnReceived(IRequest request, string connectionId, string data)
{
string where = request.Headers.Get("where");
if (where !=null&&where.Equals("windowserver"))
Connection.Broadcast(Newtonsoft.Json.JsonConvert.DeserializeObject(data), connectionId);
else
{//說明頁面需要一些請求比如添加删除修改之類東西,并且需要發送到A項目
Connection.Send(_WinServiceID, data);
}
}
}
這個時候有個問題就是A項目接受B項目發送的資料,比如B項目用戶端頁面删除,增加,修改A項目的東西,那就不能用控制台輸出,這時候需要對傳送的資料進行分析是增加還是删除還是修改。
connection.Received += data => { connection_Received(data); };//用這個替換上面代碼 connection.Received+=Console.WriteLine;
public void connection_Received(string obj)
{ //在這裡面對web發送的資料進行解析然後進行操作
switch (obj)
{
case "delete":
break;
default: //包含添加跟更新兩種指令
break;
}
}
頁面javaScript的用戶端連接配接我就不貼出代碼了,那些百度搜尋資料很多也可以看下面給出的連結位址。
這樣就完成一個簡單的兩個項目之間的通訊,兩者之間可以互相利用JSON通訊。
SignalR參考連結:
https://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr#run
http://www.cnblogs.com/Wddpct/p/5650015.html#2.1