我在服务器应用程序中使用servicestack。 这是启动服务的代码:
public override void Configure(Container container)
{
LogManager.LogFactory = new KCServiceObjects.ServiceLoggerFactory();
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
Plugins.Add(new ServerEventsFeature()
{
HeartbeatInterval = TimeSpan.FromSeconds(60),
NotifyChannelOfSubscriptions = true,
});
Plugins.Add(new ValidationFeature());
container.Register<IServerEvents>(c => new MemoryServerEvents());
notifier = new FrontendMessages(container.Resolve<IServerEvents>(), broker);
container.Register(c => notifier);
container.Register<IWebServiceEventManager>(c =>
new WebServiceEventManager(broker));
SetConfig(new HostConfig
{
DebugMode = true,
DefaultContentType = MimeTypes.Json,
EnableFeatures = Feature.All.Remove(Feature.Html),
GlobalResponseHeaders =
{
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE" },
{ "Access-Control-Allow-Headers", "Content-Type" },
},
});
}
这是.NET客户端:
clientEvents = new ServerEventsClient(string.Format("http://{0}:{1}/", sIP, 20001), "messages");
client = (IServiceClient)(clientEvents.ServiceClient);
clientEvents.Resolver = resolver;
clientEvents.RegisterReceiver<GlobalReceiver>();
clientEvents.OnConnect = (e) =>
{
var msg = JsonObject.Parse(e.Json);
ConnectionInfo = new ServerEventConnect
{
HeartbeatIntervalMs = DefaultHeartbeatMs,
IdleTimeoutMs = DefaultIdleTimeoutMs,
}.Populate(e, msg);
ConnectionInfo.Id = msg.Get("id");
ConnectionInfo.HeartbeatUrl = msg.Get("heartbeatUrl");
ConnectionInfo.HeartbeatIntervalMs = msg.Get<long>("heartbeatIntervalMs");
ConnectionInfo.IdleTimeoutMs = msg.Get<long>("idleTimeoutMs");
ConnectionInfo.UnRegisterUrl = msg.Get("unRegisterUrl");
ConnectionInfo.UserId = msg.Get("userId");
ConnectionInfo.DisplayName = msg.Get("displayName");
ConnectionInfo.ProfileUrl = msg.Get("profileUrl");
};
目前心跳不起作用,但我确定我错过了我的代码中的某些内容。查看日志,服务器发送STOP()然后发送START()。 如何在c#中实现?客户端是否必须每隔n秒向服务器发送一条消息?
感谢所有人 莱昂纳多
答案 0 :(得分:3)
一些事情:
如果要更改间隔,还需要更改IdleTimeout,例如:
Plugins.Add(new ServerEventsFeature {
HeartbeatInterval = TimeSpan.FromSeconds(60),
IdleTimeout = TimeSpan.FromSeconds(180),
});
您无需设置NotifyChannelOfSubscriptions = true
,这是默认设置。
您无需注册MemoryServerEvents
,这是默认设置:
//container.Register<IServerEvents>(c => new MemoryServerEvents());
永远不要像在ConnectionInfo
处理程序中那样自己填充OnConnect
,如果操作不正确,可能会破坏行为。
只需注册GlobalResponseHeaders
插件,而不是添加CORS CorsFeature
,例如:
Plugins.Add(new CorsFeature());