在c#中使用服务器发送
本文关键字:服务器 | 更新日期: 2023-09-27 18:11:59
我正在使用ServiceStack。客户端使用我的服务器(这是一个aspx页面)推送的数据。
下面是我使用ServiceStack Client使用数据的代码:
using System;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;
using System.Threading;
using ServiceStack;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ServerEventConnect connectMsg = null;
var msgs = new List<ServerEventMessage>();
var commands = new List<ServerEventMessage>();
var errors = new List<Exception>();
var client = new ServerEventsClient("https://testing.leadsquared.com/ReferralCampaign/Demo")
{
OnConnect = e => PrintMsg(e),
OnCommand = e => PrintCmdMsg(e),
OnMessage = e => PrintCmMsg(e),
OnException = e => PrintExMsg(e)
}.Start();
Console.Read();
}
private static void PrintCmMsg(ServerEventMessage e)
{
if (e != null)
{
PrintMsg(e.Data);
}
}
private static void PrintExMsg(Exception e)
{
if (e != null)
{
PrintMsg(e.Message);
}
}
private static void PrintCmdMsg(ServerEventMessage e)
{
if (e != null)
{
PrintMsg(e.Data);
}
}
private static void PrintMsg(ServerEventConnect e)
{
if (e!=null)
{
PrintMsg(e.Data);
}
}
private static void PrintMsg(string x)
{
Console.WriteLine(x);
}
}
}
当我运行我的代码时,客户端在控制台上打印任何消息。ConnectionDisplayName属性是"(未连接)"。如果我订阅相同的URL使用javascript EventSource,我得到通知。
我的要求是我想用c#来使用我的服务器的数据。我怎样才能做到这一点呢?
首先,url需要是BaseUri,即在JavaScript ServerEvents客户端中使用的相同的url,例如:
var client = new ServerEventsClient(BaseUrl).Start();
尚不清楚/ReferralCampaign/Demo
是否为BaseUri。
您还需要调用Connect()
来等待客户端建立连接,例如:
await client.Connect();
然后查看消息事件,您需要调用ServiceStack服务,该服务在IServerEvents
API上发布Notify*
事件,您可以使用单独的JsonServiceClient
或ServerEventsClient
中可用的ServiceClient,例如:
client.ServiceClient.Post(new PostRawToChannel {
From = client.SubscriptionId,
Message = "Test Message",
Channel = channel ?? "*",
Selector = "cmd.announce",
});
这是一个调用聊天PostRawToChannel ServiceStack服务的例子:
public class ServerEventsServices : Service
{
public IServerEvents ServerEvents { get; set; }
public void Any(PostRawToChannel request)
{
// Ensure the subscription sending this notification is still active
var sub = ServerEvents.GetSubscriptionInfo(request.From);
if (sub == null)
throw HttpError.NotFound("Subscription {0} does not exist".Fmt(request.From));
// Check to see if this is a private message to a specific user
if (request.ToUserId != null)
{
// Only notify that specific user
ServerEvents.NotifyUserId(request.ToUserId, request.Selector, request.Message);
}
else
{
// Notify everyone in the channel for public messages
ServerEvents.NotifyChannel(request.Channel, request.Selector, request.Message);
}
}
}
我还建议查看c# ServerEventTests,以获得使用c# ServerEventClient
的完整独立示例。