在桌面应用程序中使用SignalR传输IList(Of T)

时间:2016-09-23 07:20:43

标签: vb.net signalr

我需要使用SignalR进行一些测试,因此我有两个控制台应用程序 - 首先作为SignalR集线器(服务器)和第二个SignalR客户端。我需要传输自定义对象的列表,而不是像字符串或整数这样的原始数据。我不想使用WCF因为它的复杂性。

Hub:

Imports Microsoft.AspNet.SignalR
Imports Microsoft.AspNet.SignalR.Hubs
Imports DataContract
<HubName("Repository")>
Public Class RepositoryHub
  Inherits Hub
  Public Function SelectTasks() As IList(Of Task)
    Dim tasks As New List(Of Task)
    tasks.Add(New Task With {.Id = 1, .Code = "A", .Assignment = "Assignment A"})
    tasks.Add(New Task With {.Id = 2, .Code = "B", .Assignment = "Assignment B"})
    tasks.Add(New Task With {.Id = 3, .Code = "C", .Assignment = "Assignment C"})
    Return tasks
  End Function
  Public Overrides Function OnConnected() As Threading.Tasks.Task
    Console.WriteLine(Context.ConnectionId)
    Return MyBase.OnConnected()
  End Function
End Class

Public Class Task
  Public Property Id As Integer
  Public Property Code As String
  Public Property Assignment As String
End Class

服务器:

Imports Microsoft.Owin.Hosting
Module ServerModule
  Sub Main()
    Using WebApp.Start(Of OwinConfiguration)("http://localhost:8080")
      Console.ReadLine()
    End Using
  End Sub
End Module

Public Class OwinConfiguration
  Public Sub Configuration(app As IAppBuilder)
    app.UseCors(CorsOptions.AllowAll)
    app.MapSignalR()
  End Sub
End Class

客户端:

Imports Microsoft.AspNet.SignalR.Client
Imports DataContract
Module ClientModule
  Sub Main()
    Dim repositoryHub As IHubProxy
    Dim connection As New HubConnection("http://localhost:8080")
    repositoryHub = connection.CreateHubProxy("Repository")
    repositoryHub.On(Of IList(Of Task))("SelectTasks", Sub(t)
                                                         Console.WriteLine(t.Count)
                                                       End Sub)
    connection.Start().Wait()
    repositoryHub.Invoke(Of IList(Of Task))("SelectTasks").Wait()
    Console.ReadLine()
  End Sub
End Module

总是在SelectTasks方法中达到断点,但从不在客户端的匿名Sub(t)方法中,其中是处理从服务器接收的数据。

1 个答案:

答案 0 :(得分:0)

在SignalR使用中存在误解。客户应该是这样的:

Imports Microsoft.AspNet.SignalR.Client
Imports DataContract
Module ClientModule
  Sub Main()
    Dim repositoryHub As IHubProxy
    Dim connection As New HubConnection("http://localhost:8080")
    repositoryHub = connection.CreateHubProxy("Repository")
    connection.Start().Wait()
    Dim tasks = repositoryHub.Invoke(Of IList(Of Task))("SelectTasks")
    tasks.Wait()
    Console.WriteLine(tasks.Result.Count)
    Console.ReadLine()
  End Sub
End Module