namespace WpfApplication1
{
[ServiceContract(SessionMode=SessionMode.Required, CallbackContract=typeof(IMyCallbackContract))]
public interface IMyService
{
[OperationContract(IsOneWay = true)]
void NewMessageToServer(string msg);
[OperationContract(IsOneWay = false)]
bool ServerIsResponsible();
}
[ServiceContract]
public interface IMyCallbackContract
{
[OperationContract(IsOneWay = true)]
void NewMessageToClient(string msg);
[OperationContract(IsOneWay = true)]
void ClientIsResponsible();
}
public partial class Window1 : Window
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyService
{
IMyCallbackContract callback
{
get
{
return OperationContext.Current.GetCallbackChannel<IMyCallbackContract>();
}
}
public void NewMessageToServer(string msg)
{
MessageBox.Show( msg );
}
public bool ServerIsResponsible()
{
return true;
}
}
public Window1()
{
InitializeComponent();
ServiceMetadataBehavior behavior = new
ServiceMetadataBehavior();
//behavior.HttpGetEnabled = true;
//behavior.
ServiceHost serviceHost = new
ServiceHost(
typeof(MyService),
new Uri("net.tcp://localhost:8080/"));
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(
typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexTcpBinding(),
"mex");
serviceHost.AddServiceEndpoint(
typeof(IMyService),
new NetTcpBinding(),
"ServiceEndpoint"
);
serviceHost.Open();
}
public void SendButtonClick(object sender, RoutedEventArgs e)
{
try
{
IMyCallbackContract callback = null;
callback = OperationContext.Current.GetCallbackChannel<IMyCallbackContract>();
callback.NewMessageToClient(textBox1.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
WCF Duplex Contracts
Пытаюсь разобраться с WCF, нужно написать приложение для обмена текстовыми сообщениями между клиентом и сервером.
Сервер:
Код:
callback = OperationContext.Current.GetCallbackChannel<IMyCallbackContract>();
Тут все время выдает NullReferenceException.
Руководствуюсь статьей http://msdn.microsoft.com/en-us/library/ms731184.aspx
Спасибо!
Должно помочь.