SignalR Console 앱 예
.net 허브에 메시지를 보내기 위해 signalR을 사용하는 콘솔 또는 winform 앱의 작은 예가 있습니까? .net 예제를 시도하고 위키를 살펴 봤지만 허브 (.net)와 클라이언트 (콘솔 앱) 사이의 관계가 이해가되지 않습니다 (이 예제를 찾을 수 없음). 앱에 연결할 허브의 주소와 이름 만 있으면 되나요?
누군가가 허브에 연결하고 "Hello World"또는 .net 허브가받는 것을 보내는 앱을 보여주는 작은 코드를 제공 할 수 있다면?.
추신. 잘 작동하는 표준 허브 채팅 예제가 있습니다. Cs로 허브 이름을 할당하려고하면 작동이 중지됩니다. 즉 [HubName ( "test")], 그 이유를 알고 있습니까?.
감사.
현재 콘솔 앱 코드.
static void Main(string[] args)
{
//Set connection
var connection = new HubConnection("http://localhost:41627/");
//Make proxy to hub based on hub name on server
var myHub = connection.CreateProxy("chat");
//Start connection
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
}
}).Wait();
//connection.StateChanged += connection_StateChanged;
myHub.Invoke("Send", "HELLO World ").ContinueWith(task => {
if(task.IsFaulted)
{
Console.WriteLine("There was an error calling send: {0}",task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Send Complete.");
}
});
}
Hub 서버. (다른 프로젝트 작업 공간)
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.addMessage(message);
}
}
이에 대한 정보 위키는 http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client 입니다 .
먼저 서버 애플리케이션에 SignalR.Host.Self를 설치하고 nuget을 통해 클라이언트 애플리케이션에 SignalR.Client를 설치해야합니다.
PM> Install-Package SignalR.Hosting.Self-버전 0.5.2
PM> 설치 패키지 Microsoft.AspNet.SignalR.Client
그런 다음 프로젝트에 다음 코드를 추가하십시오.)
(관리자 권한으로 프로젝트 실행)
서버 콘솔 앱 :
using System;
using SignalR.Hubs;
namespace SignalR.Hosting.Self.Samples {
class Program {
static void Main(string[] args) {
string url = "http://127.0.0.1:8088/";
var server = new Server(url);
// Map the default hub url (/signalr)
server.MapHubs();
// Start the server
server.Start();
Console.WriteLine("Server running on {0}", url);
// Keep going until somebody hits 'x'
while (true) {
ConsoleKeyInfo ki = Console.ReadKey(true);
if (ki.Key == ConsoleKey.X) {
break;
}
}
}
[HubName("CustomHub")]
public class MyHub : Hub {
public string Send(string message) {
return message;
}
public void DoSomething(string param) {
Clients.addMessage(param);
}
}
}
}
클라이언트 콘솔 앱 :
using System;
using SignalR.Client.Hubs;
namespace SignalRConsoleApp {
internal class Program {
private static void Main(string[] args) {
//Set connection
var connection = new HubConnection("http://127.0.0.1:8088/");
//Make proxy to hub based on hub name on server
var myHub = connection.CreateHubProxy("CustomHub");
//Start connection
connection.Start().ContinueWith(task => {
if (task.IsFaulted) {
Console.WriteLine("There was an error opening the connection:{0}",
task.Exception.GetBaseException());
} else {
Console.WriteLine("Connected");
}
}).Wait();
myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => {
if (task.IsFaulted) {
Console.WriteLine("There was an error calling send: {0}",
task.Exception.GetBaseException());
} else {
Console.WriteLine(task.Result);
}
});
myHub.On<string>("addMessage", param => {
Console.WriteLine(param);
});
myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait();
Console.Read();
connection.Stop();
}
}
}
SignalR 2.2.1의 예 (2017 년 5 월)
섬기는 사람
설치 패키지 Microsoft.AspNet.SignalR.SelfHost-버전 2.2.1
[assembly: OwinStartup(typeof(Program.Startup))]
namespace ConsoleApplication116_SignalRServer
{
class Program
{
static IDisposable SignalR;
static void Main(string[] args)
{
string url = "http://127.0.0.1:8088";
SignalR = WebApp.Start(url);
Console.ReadKey();
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
/* CAMEL CASE & JSON DATE FORMATTING
use SignalRContractResolver from
https://stackoverflow.com/questions/30005575/signalr-use-camel-case
var settings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
settings.ContractResolver = new SignalRContractResolver();
var serializer = JsonSerializer.Create(settings);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
*/
app.MapSignalR();
}
}
[HubName("MyHub")]
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
}
고객
(Mehrdad Bahrainy 응답과 거의 동일)
Install-Package Microsoft.AspNet.SignalR.Client-버전 2.2.1
namespace ConsoleApplication116_SignalRClient
{
class Program
{
private static void Main(string[] args)
{
var connection = new HubConnection("http://127.0.0.1:8088/");
var myHub = connection.CreateHubProxy("MyHub");
Console.WriteLine("Enter your name");
string name = Console.ReadLine();
connection.Start().ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
myHub.On<string, string>("addMessage", (s1, s2) => {
Console.WriteLine(s1 + ": " + s2);
});
while (true)
{
string message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
{
break;
}
myHub.Invoke<string>("Send", name, message).ContinueWith(task1 => {
if (task1.IsFaulted)
{
Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
}
else
{
Console.WriteLine(task1.Result);
}
});
}
}
}).Wait();
Console.Read();
connection.Stop();
}
}
}
The Self-Host now uses Owin. Checkout http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host to setup the server. It's compatible with the client code above.
참고URL : https://stackoverflow.com/questions/11140164/signalr-console-app-example
'programing' 카테고리의 다른 글
SQL Server 데이터베이스의 모든 테이블에서 특정 유형의 모든 열 찾기 (0) | 2020.10.19 |
---|---|
imshow () 그림이 너무 작습니다. (0) | 2020.10.19 |
오류 CS0433 "A.dll과 B.dll에 이미 'X'유형이 있습니다."라는 오류는 어디에서 발생합니까? (0) | 2020.10.18 |
컨텍스트 루트 이름을 포함하지 않고 상대 경로를 사용하는 방법은 무엇입니까? (0) | 2020.10.18 |
전체 텍스트 인덱싱이 아니므로 테이블 또는 인덱싱 된 뷰에서 CONTAINS 또는 FREETEXT 조건자를 사용할 수 없습니다. (0) | 2020.10.18 |