这是我的服务器应用程序代码:
[ServiceContract]
public interface IFirst
{
[OperationContract]
void First();
}
[ServiceContract]
public interface ISecond
{
[OperationContract]
void Second();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class Service : IFirst, ISecond
{
static int count = 0;
int serviceID;
public Service()
{
serviceID = ++count;
Console.WriteLine("Service {0} created.", serviceID);
}
public void First()
{
Console.WriteLine("First function. ServiceID: {0}", serviceID);
}
public void Second()
{
Console.WriteLine("Second function. ServiceID: {0}", serviceID);
}
}
class Server
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(Service), new Uri("net.tcp://localhost:8000"));
NetTcpBinding binding = new NetTcpBinding();
host.AddServiceEndpoint(typeof(IFirst), binding, "");
host.AddServiceEndpoint(typeof(ISecond), binding, "");
host.Open();
Console.WriteLine("Successfully opened port 8000.");
Console.ReadLine();
host.Close();
}
}
和客户:
class Client
{
static void Main(string[] args)
{
ChannelFactory<IFirst> firstFactory = new ChannelFactory<IFirst>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8000"));
IFirst iForst = firstFactory.CreateChannel();
iForst.First();
ChannelFactory<ISecond> secondFactory = new ChannelFactory<ISecond>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8000"));
ISecond iSecond = secondFactory.CreateChannel();
iSecond.Second();
Console.ReadLine();
}
}
当我运行它时,我得到输出:
Successfully opened port 8000.
Service 1 created.
First function. ServiceID: 1
Service 2 created.
Second function. ServiceID: 2
在我的例子中,服务器创建了两个服务实例。我想要做的是为 First 所做的同一个 Service 实例调用 Second 函数。