摘要:Visual Studio 2010 SignalR Persistent Connection(ASP.NET Server and Windows Form Client)
Complete source : https://onedrive.live.com/redir?resid=FBEB6373D9321A7F!271132&authkey=!AHjIzYYHd9PUDOg&ithint=file%2czip
ASP.NET Server and Windows Form Client
Add ASP.NET Empty Web Application
Project Nuget install Microsoft ASP.NET SignalR 1.2.2(The lastest version in Visual Studio 2010 with .net framework 4.0)
PM> Install-Package Microsoft.AspNet.SignalR -Version 1.2.2
Add Default.aspx
Add Global Application Class called Global.asax
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapConnection<EchoConnection>("EchoConnection", "/realtime/echo");
}
Add a cs file called EchoConnection.cs
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR.Infrastructure;
using System.Web;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System;
using System.Diagnostics;
namespace WebAppSingalRServer
{
public class EchoConnection : PersistentConnection
{
private static int _connections = 0;
protected override Task OnConnected(IRequest request, string connectionId)
{
Interlocked.Increment(ref _connections);
string sendMsg = "Setting," + connectionId;
return Connection.Send(connectionId, sendMsg);
}
protected override Task OnDisconnected(IRequest request, string connectionId)
{
Interlocked.Decrement(ref _connections);
return null;
}
protected override Task OnReceived(IRequest request, string connectionId, string data)
{
string[] strArray = data.Split(',');
string szCommand = strArray[0];
if (szCommand == "abc")
{
try
{
//return Connection.Broadcast("def");
return Connection.Send(connectionId, "def");
}
catch (Exception ex)
{
Debug.WriteLine("Exception = " + ex.ToString());
return null;
}
}
return null;
}
}
}
Create a windows form for client
Add a windows form called SignalClient and add a button on it
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.AspNet.SignalR;
//using Microsoft.AspNet.SignalR.Client.Hubs;
using System.Diagnostics;
using Microsoft.AspNet.SignalR.Client;
namespace WinFormSignalR
{
public partial class SignalClient : Form
{
public Connection PersistentConnection;
public SignalClient()
{
InitializeComponent();
PersistentConnection= new Connection("http://localhost:6684/realtime/echo");
PersistentConnection.Received += ReceivedMessage;
PersistentConnection.Start().Wait();
}
private void ReceivedMessage(string str)
{
Debug.WriteLine("str = " + str);
}
private void button1_Click(object sender, EventArgs e)
{
PersistentConnection.Send("abc").Wait();
}
}
}