SuperSocket 1.4系列文档(14) 多服务器实例和服务器实例之间的交互
SuperSocket支持在同一程序中运行多个服务器实例监听在不同的IP或端口,只需在配置文件中添加两个server节点即可:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="socketServer" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/>
</configSections>
<appSettings>
<add key="ServiceName" value="SuperSocket"/>
</appSettings>
<socketServer>
<servers>
<server name="ServerA"
serviceName="MyAppServerA"
ip="Any" port="911" mode="Async">
</server>
<server name="ServerB"
serviceName="MyAppServerB"
ip="Any" port="912" mode="Async">
</server>
</servers>
<services>
<service name="MyAppServerA"
type="SuperSocket.QuickStart.MultipleAppServer.MyAppServerA, SuperSocket.QuickStart.MultipleAppServer" />
<service name="MyAppServerB"
type="SuperSocket.QuickStart.MultipleAppServer.MyAppServerB, SuperSocket.QuickStart.MultipleAppServer" />
</services>
</socketServer>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
</configuration>
在某些情况下,需要两个服务器实例之间进行交互。例如ServerA上的客户端C1向ServerB上的客户端C2转发消息,这样就需要ServerA接收到C1的命令之后通过ServerB将消息转发给客户端C2。
在MyAppServerA的OnStartup方法里面可利用SocketServerManager的GetServerByName(string name)方法通过服务器实例的名称来获取服务器实例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
namespace SuperSocket.QuickStart.MultipleAppServer
{
public class MyAppServerA : AppServer
{
private IDespatchServer m_DespatchServer;
protected override void OnStartup()
{
m_DespatchServer = SocketServerManager.GetServerByName("ServerB") as IDespatchServer;
base.OnStartup();
}
internal void DespatchMessage(string targetSessionKey, string message)
{
m_DespatchServer.DispatchMessage(targetSessionKey, message);
}
}
interface IDespatchServer
{
void DispatchMessage(string sessionKey, string message);
}
public class MyAppServerB : AppServer, IDespatchServer
{
public void DispatchMessage(string sessionKey, string message)
{
var session = GetAppSessionByIndentityKey(sessionKey);
if (session == null)
return;
session.SendResponse(message);
}
}
}
这样就可以在MyAppServerA中通过调用MyAppServerB实例的方法来向ServerB的客户端发送消息了。
示例代码请参考SuperSocket源代码QuickStart中的MultipleAppServer项目。