private void _LogOut() { if (LobbyViewModel.Instance.Connection != null) { try { LobbyViewModel.Instance.Connection.Logout(); LobbyViewModel.Instance.Connection = null; } catch (Exception) { } } if (_channelFactory != null) { try { _channelFactory.Close(); } catch (Exception) { _channelFactory.Abort(); } _channelFactory = null; } }
// DuplexChannelBase IPeerConnectorClient CreateInnerClient(RemotePeerConnection conn) { conn.Instance = new LocalPeerReceiver(this); conn.Instance.WelcomeReceived += delegate(WelcomeInfo welcome) { conn.NodeId = welcome.NodeId; // FIXME: handle referrals }; // FIXME: pass more setup parameters var binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; var channel_factory = new DuplexChannelFactory <IPeerConnectorClient> (conn.Instance, binding); channel_factory.Open(); var ch = channel_factory.CreateChannel(new EndpointAddress("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri); ch.Closed += delegate { channel_factory.Close(); }; return(ch); }
public void Destroy() { manual_close = true; cf.Close(); cf = null; srv = null; }
static void Main(string[] args) { var channelFactory = new DuplexChannelFactory<IChatService>(new ChatClientImpl(), "ChatServiceEndpoint"); var server = channelFactory.CreateChannel(); server.Login(Environment.UserName); Console.WriteLine("Current Users:"); foreach(var user in server.LoggedInUsers) Console.WriteLine(user.UserName); Console.WriteLine(); Console.WriteLine("Enter text and press <Enter> to send a message."); Console.WriteLine("Enter '!quit' to disconnect and exit."); string message = Console.ReadLine(); while(message != "!quit") { message = message.Trim(); if(!string.IsNullOrEmpty(message)) server.SendMessage(message); message = Console.ReadLine(); } server.Logout(); channelFactory.Close(); }
void ConnectToService() { var client = new Client(this); var time = TimeSpan.FromSeconds(0.2); var binding = new NetNamedPipeBinding { CloseTimeout = time, OpenTimeout = time, ReceiveTimeout = time }; if (factory != null) { try { factory.Close(); } catch { } } factory = new DuplexChannelFactory <INfaServiceNotify>(new InstanceContext(client), binding, new EndpointAddress("net.pipe://localhost/netfree-anywhere/control")); service = factory.CreateChannel(); try { service.SubscribeClient(); } catch (Exception) { } }
public void Dispose() { if (mDisposed) { return; } try { if (mParticipant != null) { mParticipant.Leave(mNodeName); //mParticipant.Close(); //mParticipant.Abort(); } } catch (InvalidOperationException) { //safely ignore. This exception occurs when we are in the process of opening when they quit the application. //catch the exception to ignore it. } if (mFactory != null) { mFactory.Close(); } mParticipant.Abort(); mParticipant.Dispose(); mParticipant = null; mDisposed = true; }
public static void logoff(string userName) { bool isFault = false; try { proxy.LogOut(userName); Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Client {userName} logged out"); factory.Close(); Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Channel for Client {userName} closed"); StopConnectionTimer(); } catch (Exception e) { isFault = true; Report.log(DeviceToReport.Client_Proxy, LogLevel.Exception, e.Message); throw e; } finally { if (isFault) { factory.Abort(); Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Channel closed for client {userName} after exception"); OpenChannel(); Report.log(DeviceToReport.Client_Proxy, LogLevel.Information, $"Channel opened for client {userName} after exception"); } } }
static void Main() { Console.Title = "UserChatWindow"; var client = new MyChatClient(); var address = new Uri("net.tcp://*****:*****@"..\..\..\HumanConsole\bin\Debug\HumanConsole.exe"); Console.ReadKey(true); chatWindowhost.Close(); factory.Close(); }
public static void RequestResponseOverWebSocketManually_Echo_RoundTrips_Guid() { DuplexChannelFactory <IWcfDuplexService> factory = null; IWcfDuplexService duplexProxy = null; Guid guid = Guid.NewGuid(); try { // *** SETUP *** \\ NetHttpBinding binding = new NetHttpBinding(); binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callbackService); factory = new DuplexChannelFactory <IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address)); duplexProxy = factory.CreateChannel(); // *** EXECUTE *** \\ Task.Run(() => duplexProxy.Ping(guid)); Guid returnedGuid = callbackService.CallbackGuid; // *** VALIDATE *** \\ Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)duplexProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)duplexProxy, factory); } }
/// <summary> /// 释放连接 /// </summary> public void Dispose() { UnConnection(); try { if (mChannelFactory != null) { mChannelFactory.Close(); } if (mfileChannelFactory != null) { mfileChannelFactory.Close(); } } catch { if (mChannelFactory != null) { mChannelFactory.Abort(); } if (mfileChannelFactory != null) { mfileChannelFactory.Abort(); } } }
public void Dispose() { log.Info("Disposing of service proxy"); if (client != null) { try { client.Unsubscribe(); } catch (Exception) { } finally { client = null; } } ; if (clientFactory != null) { try { clientFactory.Close(); } catch (Exception) { } finally { clientFactory = null; } } }
public void Disconnect() { if (_factory != null) { _factory.Close(); } }
public static void RequestResponseOverWebSocketManually_Echo_RoundTrips_Guid() { DuplexChannelFactory<IWcfDuplexService> factory = null; IWcfDuplexService duplexProxy = null; Guid guid = Guid.NewGuid(); try { // *** SETUP *** \\ NetHttpBinding binding = new NetHttpBinding(); binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callbackService); factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address)); duplexProxy = factory.CreateChannel(); // *** EXECUTE *** \\ Task.Run(() => duplexProxy.Ping(guid)); Guid returnedGuid = callbackService.CallbackGuid; // *** VALIDATE *** \\ Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)duplexProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)duplexProxy, factory); } }
private void Disconnect() { _callBack.NewInstanceEvent -= new EventHandler(_callBack_NewInstanceEvent); MainWindow.BindingData.Disconnect(); _channel.Close(); BindingData.Connected = false; }
static void Main(string[] args) { var channelFactory = new DuplexChannelFactory <IChatService>(new ChatClientImpl(), "ChatServiceEndpoint"); var server = channelFactory.CreateChannel(); server.Login(Environment.UserName); Console.WriteLine("Current Users:"); foreach (var user in server.LoggedInUsers) { Console.WriteLine(user.UserName); } Console.WriteLine(); Console.WriteLine("Enter text and press <Enter> to send a message."); Console.WriteLine("Enter '!quit' to disconnect and exit."); string message = Console.ReadLine(); while (message != "!quit") { message = message.Trim(); if (!string.IsNullOrEmpty(message)) { server.SendMessage(message); } message = Console.ReadLine(); } server.Logout(); channelFactory.Close(); }
private static void joinChatroom(int port, string username) { DuplexChannelFactory <Chatroom> dupFactory = null; Chatroom clientProxy = null; TextChatter _chatter = new TextChatter(); dupFactory = new DuplexChannelFactory <Chatroom>( _chatter, new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:" + port + "/Chat")); dupFactory.Open(); clientProxy = dupFactory.CreateChannel(); Console.WriteLine("Bienvenue dans la room {0}", username); clientProxy.join(username); string input = null; while (input != "exit") { input = Console.ReadLine(); clientProxy.send(input, username); Console.SetCursorPosition(0, Console.CursorTop - 2); ClearCurrentConsoleLine(); Console.SetCursorPosition(0, Console.CursorTop + 2); } dupFactory.Close(); }
public static void Close() { if (pipeFactory.State != CommunicationState.Closed && pipeFactory.State != CommunicationState.Faulted) { pipeFactory.Close(); } }
//其他成员 private void MonitorForm_Load(object sender, EventArgs e) { string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event"); this.listBoxExecutionProgress.Items.Add(header); _syncContext = SynchronizationContext.Current; _callbackInstance = new InstanceContext(new CalculatorCallbackService()); _channelFactory = new DuplexChannelFactory<ICalculator>(_callbackInstance, "calculatorservice"); EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification; this.Disposed += delegate { EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification; _channelFactory.Close(); }; for (int i = 0; i < 2; i++) { ThreadPool.QueueUserWorkItem(state => { int clientId = Interlocked.Increment(ref _clientId); EventMonitor.Send(clientId, EventType.StartCall); ICalculator proxy = _channelFactory.CreateChannel(); using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel)) { MessageHeader<int> messageHeader = new MessageHeader<int>(clientId); OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace)); proxy.Add(1, 2); } EventMonitor.Send(clientId, EventType.EndCall); }, null); } }
public void End() { try { if (IsConnected) { if (participant != null) { participant.Leave(member); participant.Close(); participant.Dispose(); } if (factory != null) { factory.Close(); } } IsConnected = false; } catch (Exception) { } }
private void ConnectToServer(Client client) { try { if (channel != null) { channel.Close(); } NetTcpBinding binding = new NetTcpBinding(); EndpointAddress endpoint = new EndpointAddress(Names.Address); AddMsgToChat("connecting as " + client.clientAD + " to ChatServerEndPoint"); channel = new DuplexChannelFactory <IServer>( client, binding, endpoint + "/" + Names.Endpoint); chatServerProxy = channel.CreateChannel(); //RecieveClientsUpdate called after register chatServerProxy.Register(client.clientAD); AddMsgToChat("CONNECTED TO SERVER"); } catch (Exception ex) { AddMsgToChat("COULD NOT CONNECT TO SERVER"); AddMsgToChat(ex.ToString()); } }
/// <summary> /// Use this for contracts which have a callback interface. /// </summary> public static void UsingDuplex <TServiceContract>(Action <TServiceContract> action, object callbackImplementation, string endpointConfigurationName) { using (var channelFactory = new DuplexChannelFactory <TServiceContract>(callbackImplementation, endpointConfigurationName)) { channelFactory.Open(); var success = false; try { var client = channelFactory.CreateChannel(); action(client); if (channelFactory.State != CommunicationState.Faulted) { channelFactory.Close(); success = true; } } finally { if (!success) { channelFactory.Abort(); } } } }
public static void Test() { string baseAddress = "net.tcp://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); host.AddServiceEndpoint(typeof(ITest), new NetTcpBinding(SecurityMode.None), ""); host.Open(); Console.WriteLine("Host opened"); AutoResetEvent evt = new AutoResetEvent(false); MyCallback callback = new MyCallback(evt); DuplexChannelFactory <ITest> factory = new DuplexChannelFactory <ITest>( new InstanceContext(callback), new NetTcpBinding(SecurityMode.None), new EndpointAddress(baseAddress)); ITest proxy = factory.CreateChannel(); Console.WriteLine(proxy.Hello("foo bar")); evt.WaitOne(); ((IClientChannel)proxy).Close(); factory.Close(); Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); }
public static void Test() { string baseAddress = "net.tcp://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); host.AddServiceEndpoint(typeof(ITest), new NetTcpBinding(SecurityMode.None), ""); host.Open(); Console.WriteLine("Host opened"); AutoResetEvent evt = new AutoResetEvent(false); MyCallback callback = new MyCallback(evt); DuplexChannelFactory<ITest> factory = new DuplexChannelFactory<ITest>( new InstanceContext(callback), new NetTcpBinding(SecurityMode.None), new EndpointAddress(baseAddress)); ITest proxy = factory.CreateChannel(); Console.WriteLine(proxy.Hello("foo bar")); evt.WaitOne(); ((IClientChannel)proxy).Close(); factory.Close(); Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); }
public ChatWCFClient(string ipAddress, IChatServiceCallback callback) { try { m_ipAddress = ipAddress; NetTcpBinding tcpBinding = new NetTcpBinding(); tcpBinding.OpenTimeout = TimeSpan.FromSeconds(5); tcpBinding.ReceiveTimeout = TimeSpan.FromSeconds(5); tcpBinding.SendTimeout = TimeSpan.FromSeconds(5); tcpBinding.CloseTimeout = TimeSpan.FromSeconds(5); tcpBinding.MaxConnections = 2000; tcpBinding.TransactionFlow = false; //tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign; //tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; //tcpBinding.Security.Mode = SecurityMode.Transport; pipeFactory = new DuplexChannelFactory <IChatService>( new InstanceContext(callback), tcpBinding, new EndpointAddress("net.tcp://" + ipAddress + ":8099/ChatService")); m_client = pipeFactory.CreateChannel(); } catch (Exception err) { pipeFactory.Close(); throw (new SystemException(err.Message)); } }
private void Window_Closed(object sender, EventArgs e) { if (factory != null) { factory.Close(); } }
static void Main(string[] args) { var channelFactory = new DuplexChannelFactory <IChatService>(new ChatClientImpl(), "ChatServiceEndpoint"); var server = channelFactory.CreateChannel(); server.Login(Environment.UserName); Console.WriteLine("Usuarios actuales:"); foreach (var user in server.LoggedInUsers) { Console.WriteLine(user.UserName); } Console.WriteLine(); Console.WriteLine("Ingrese el texto y presione <Enter> para enviar el mensaje."); Console.WriteLine("Presione el comando '<quit>' para desconectarse y salir del chat."); string message = Console.ReadLine(); while (message != "<quit>") { message = message.Trim(); if (!string.IsNullOrEmpty(message)) { server.SendMessage(message); } message = Console.ReadLine(); } server.Logout(); channelFactory.Close(); }
static void Main(string[] args) { DuplexChannelFactory <IFolderContentServer> factory = null; try { Console.Title = "ChannelClient"; Task.Delay(1000).Wait(); var client = new FolderContentClient(); factory = new DuplexChannelFactory <IFolderContentServer>(client, "FolderContentClientEndPoint"); var channel = factory.CreateChannel(); Console.WriteLine("Здесь и далее: введите путь каталога и нажмите <ENTER>"); while (true) { var path = Console.ReadLine(); channel.RequestContent(path); Console.WriteLine("----------Я НЕ ЗАБЛОКИРОВАН!----------{0}\tРезультат:", Environment.NewLine); } } catch (Exception e) { Console.WriteLine(e); } finally { if (factory != null) { factory.Close(); } } }
public static void NetTcpBinding_DuplexCallback_ReturnsXmlComplexType() { DuplexChannelFactory <IWcfDuplexService_Xml> factory = null; NetTcpBinding binding = null; WcfDuplexServiceCallback callbackService = null; InstanceContext context = null; IWcfDuplexService_Xml serviceProxy = null; Guid guid = Guid.NewGuid(); try { binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; callbackService = new WcfDuplexServiceCallback(); context = new InstanceContext(callbackService); factory = new DuplexChannelFactory <IWcfDuplexService_Xml>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_XmlDuplexCallback_Address)); serviceProxy = factory.CreateChannel(); serviceProxy.Ping_Xml(guid); XmlCompositeTypeDuplexCallbackOnly returnedType = callbackService.XmlCallbackGuid; // validate response Assert.True((guid.ToString() == returnedType.StringValue), String.Format("The Guid to string value sent was not the same as what was returned.\nSent: {0}\nReturned: {1}", guid.ToString(), returnedType.StringValue)); ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void WebSocket_Http_Duplex_Buffered(NetHttpMessageEncoding messageEncoding) { EndpointAddress endpointAddress; NetHttpBinding binding = null; ClientReceiver clientReceiver = null; InstanceContext context = null; DuplexChannelFactory <IWSDuplexService> channelFactory = null; IWSDuplexService client = null; try { // *** SETUP *** \\ binding = new NetHttpBinding() { MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB, MaxBufferSize = ScenarioTestHelpers.SixtyFourMB, }; binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; binding.MessageEncoding = messageEncoding; clientReceiver = new ClientReceiver(); context = new InstanceContext(clientReceiver); endpointAddress = new EndpointAddress(Endpoints.WebSocketHttpDuplexBuffered_Address + Enum.GetName(typeof(NetHttpMessageEncoding), messageEncoding)); channelFactory = new DuplexChannelFactory <IWSDuplexService>(context, binding, endpointAddress); client = channelFactory.CreateChannel(); // *** EXECUTE *** \\ // Invoking UploadData client.UploadData(ScenarioTestHelpers.CreateInterestingString(123)); // Invoking StartPushingData client.StartPushingData(); Assert.True(clientReceiver.ReceiveDataInvoked.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the buffered response from the Service. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); clientReceiver.ReceiveDataInvoked.Reset(); // Invoking StopPushingData client.StopPushingData(); Assert.True(clientReceiver.ReceiveDataCompleted.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the buffered response from the Service to be completed. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); clientReceiver.ReceiveDataCompleted.Reset(); // Getting results from server via callback. client.GetLog(); Assert.True(clientReceiver.LogReceived.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the Logging from the Service to be received. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); // *** VALIDATE *** \\ Assert.True(clientReceiver.ServerLog.Count > 0, "The logging done by the Server was not returned via the Callback."); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); channelFactory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory); } }
public static async void CallbackBehavior_ConcurrencyMode_Multiple_NetTcpBinding() { NetTcpBinding binding; InstanceContext instanceContext; DuplexChannelFactory <IWcfDuplexService_CallbackConcurrencyMode> factory; IWcfDuplexService_CallbackConcurrencyMode channel; // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.None); var imp = new CallbackHandler_ConcurrencyMode_Multiple(new ManualResetEvent(false)); instanceContext = new InstanceContext(imp); factory = new DuplexChannelFactory <IWcfDuplexService_CallbackConcurrencyMode>(instanceContext, binding, Endpoints.DuplexCallbackConcurrencyMode_Address); // *** EXECUTE *** \\ channel = factory.CreateChannel(); Task task = channel.DoWorkAsync(); // *** VALIDATE *** \\ Assert.True(imp.ManualResetEvent.WaitOne(20000)); Assert.Equal(2, imp.Counter); await task; // *** CLEANUP *** \\ ((ICommunicationObject)channel).Close(); factory.Close(); }
static void Main(string[] args) { DuplexChannelFactory <IDuplexSvc> factory = null; try { Console.Title = "ChannelClient"; Task.Delay(1000).Wait(); var client = new Ex13ClientCallback(); factory = new DuplexChannelFactory <IDuplexSvc>(client, "MyEndPoint"); var channel = factory.CreateChannel(); Console.WriteLine("Ожидается ответ:"); channel.ReturnTime(1, 10); Console.ReadKey(true); } catch (Exception e) { Console.WriteLine(e); } finally { if (factory != null) { factory.Close(); } } }
//其他成员 private void MonitorForm_Load(object sender, EventArgs e) { string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event"); this.listBoxExecutionProgress.Items.Add(header); _syncContext = SynchronizationContext.Current; _callbackInstance = new InstanceContext(new CalculatorCallbackService()); _channelFactory = new DuplexChannelFactory <ICalculator>(_callbackInstance, "calculatorservice"); EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification; this.Disposed += delegate { EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification; _channelFactory.Close(); }; for (int i = 0; i < 2; i++) { ThreadPool.QueueUserWorkItem(state => { int clientId = Interlocked.Increment(ref _clientId); EventMonitor.Send(clientId, EventType.StartCall); ICalculator proxy = _channelFactory.CreateChannel(); using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel)) { MessageHeader <int> messageHeader = new MessageHeader <int>(clientId); OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace)); proxy.Add(1, 2); } EventMonitor.Send(clientId, EventType.EndCall); }, null); } }
public static void ServiceContract_TypedProxy_AsyncTask_CallbackReturn() { DuplexChannelFactory <IWcfDuplexTaskReturnService> factory = null; Guid guid = Guid.NewGuid(); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback(); InstanceContext context = new InstanceContext(callbackService); try { factory = new DuplexChannelFactory <IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address)); IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel(); Task <Guid> task = serviceProxy.Ping(guid); Guid returnedGuid = task.Result; Assert.Equal(guid, returnedGuid); factory.Close(); } finally { if (factory != null && factory.State != CommunicationState.Closed) { factory.Abort(); } } }
public void Dispose() { _manualClose = true; _cf.Close(); Service = default; ((IDisposable)_cf)?.Dispose(); }
public static void NetTcpBinding_DuplexCallback_ReturnsXmlComplexType() { DuplexChannelFactory<IWcfDuplexService_Xml> factory = null; NetTcpBinding binding = null; WcfDuplexServiceCallback callbackService = null; InstanceContext context = null; IWcfDuplexService_Xml serviceProxy = null; Guid guid = Guid.NewGuid(); try { binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; callbackService = new WcfDuplexServiceCallback(); context = new InstanceContext(callbackService); factory = new DuplexChannelFactory<IWcfDuplexService_Xml>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_XmlDuplexCallback_Address)); serviceProxy = factory.CreateChannel(); serviceProxy.Ping_Xml(guid); XmlCompositeTypeDuplexCallbackOnly returnedType = callbackService.XmlCallbackGuid; // validate response Assert.True((guid.ToString() == returnedType.StringValue), String.Format("The Guid to string value sent was not the same as what was returned.\nSent: {0}\nReturned: {1}", guid.ToString(), returnedType.StringValue)); ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void ServiceContract_TypedProxy_AsyncTask_CallbackReturn() { DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null; Guid guid = Guid.NewGuid(); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback(); InstanceContext context = new InstanceContext(callbackService); try { factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address)); IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel(); Task<Guid> task = serviceProxy.Ping(guid); Guid returnedGuid = task.Result; Assert.Equal(guid, returnedGuid); factory.Close(); } finally { if (factory != null && factory.State != CommunicationState.Closed) { factory.Abort(); } } }
static void Main(string[] args) { var channelFactory = new DuplexChannelFactory<ILobbyService>(new GameClientImpl(), "GameServiceEndpoint"); ILobbyService server = channelFactory.CreateChannel(); LoginToken token; server.Login(1, "DaMuBie", out token); // Do some stuff such as reading messages from the user and sending them to the server var room = server.CreateRoom(token); server.Logout(token); channelFactory.Close(); }
public static void ServiceContract_TypedProxy_DuplexCallback() { DuplexChannelFactory<IDuplexChannelService> factory = null; StringBuilder errorBuilder = new StringBuilder(); Guid guid = Guid.NewGuid(); try { NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; DuplexChannelServiceCallback callbackService = new DuplexChannelServiceCallback(); InstanceContext context = new InstanceContext(callbackService); factory = new DuplexChannelFactory<IDuplexChannelService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_DuplexCallback_Address)); IDuplexChannelService serviceProxy = factory.CreateChannel(); serviceProxy.Ping(guid); Guid returnedGuid = callbackService.CallbackGuid; if (guid != returnedGuid) { errorBuilder.AppendLine(String.Format("The sent GUID does not match the returned GUID. Sent: {0} Received: {1}", guid, returnedGuid)); } factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException) { errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString())); } } finally { if (factory != null && factory.State != CommunicationState.Closed) { factory.Abort(); } } if (errorBuilder.Length != 0) { Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: ServiceContract_TypedProxy_DuplexCallback FAILED with the following errors: {0}", errorBuilder)); } }
private static void Main(string[] args) { string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event"); Console.WriteLine(header); Console.WriteLine("Press any key to run clients"); Console.ReadKey(); _syncContext = SynchronizationContext.Current; _callbackInstance = new InstanceContext(new CalculatorCallbackService()); //Create DuplexChannel _channelFactory = new DuplexChannelFactory<ICalculator>(_callbackInstance, "calculatorservice"); EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification; for (int i = 0; i < 5; i++) { ThreadPool.QueueUserWorkItem(state => { int clientId = Interlocked.Increment(ref _clientId); EventMonitor.Send(clientId, EventType.StartCall); ICalculator proxy = _channelFactory.CreateChannel(); using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel)) { MessageHeader<int> messageHeader = new MessageHeader<int>(clientId); OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace)); proxy.Add(1, 2); } EventMonitor.Send(clientId, EventType.EndCall); }, null); } Console.WriteLine("Press any key to exit.Client"); header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event"); Console.WriteLine(header); Console.ReadKey(); EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification; _channelFactory.Close(); }
public static void ServiceContract_TypedProxy_DuplexCallback() { NetTcpBinding binding = null; DuplexChannelFactory<IDuplexChannelService> factory = null; Guid guid = Guid.NewGuid(); DuplexChannelServiceCallback callbackService = null; InstanceContext context = null; EndpointAddress endpointAddress = null; IDuplexChannelService serviceProxy = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; callbackService = new DuplexChannelServiceCallback(); context = new InstanceContext(callbackService); endpointAddress = new EndpointAddress(Endpoints.Tcp_NoSecurity_DuplexCallback_Address); factory = new DuplexChannelFactory<IDuplexChannelService>(context, binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ serviceProxy.Ping(guid); Guid returnedGuid = callbackService.CallbackGuid; // *** VALIDATE *** \\ Assert.True(guid == returnedGuid, String.Format("The sent GUID does not match the returned GUID. Sent: {0} Received: {1}", guid, returnedGuid)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
static void Main(string[] args) { string baseAddress = SizedTcpDuplexTransportBindingElement.SizedTcpScheme + "://localhost:8000"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); Binding binding = new CustomBinding(new SizedTcpDuplexTransportBindingElement()); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), binding, ""); host.Open(); Console.WriteLine("Host opened"); InstanceContext instanceContext = new InstanceContext(new ClientCallback()); EndpointAddress endpointAddress = new EndpointAddress(baseAddress); DuplexChannelFactory<ITest> factory = new DuplexChannelFactory<ITest>(instanceContext, binding, endpointAddress); ITest proxy = factory.CreateChannel(); proxy.Hello("John Doe"); Console.WriteLine("Press ENTER to close"); Console.ReadLine(); ((IClientChannel)proxy).Close(); factory.Close(); host.Close(); }
private static void joinChatroom(int port, string username) { DuplexChannelFactory<Chatroom> dupFactory = null; Chatroom clientProxy = null; TextChatter _chatter = new TextChatter(); dupFactory = new DuplexChannelFactory<Chatroom>( _chatter, new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:"+ port +"/Chat")); dupFactory.Open(); clientProxy = dupFactory.CreateChannel(); Console.WriteLine("Bienvenue dans la room {0}",username); clientProxy.join(username); string input = null; while (input != "exit") { input = Console.ReadLine(); clientProxy.send(input, username); Console.SetCursorPosition(0, Console.CursorTop - 2); ClearCurrentConsoleLine(); Console.SetCursorPosition(0, Console.CursorTop + 2); } dupFactory.Close(); }
public static void WebSocket_Http_Duplex_TextBuffered_KeepAlive() { NetHttpBinding binding = null; ClientReceiver clientReceiver = null; InstanceContext context = null; DuplexChannelFactory<IWSDuplexService> channelFactory = null; IWSDuplexService client = null; try { // *** SETUP *** \\ binding = new NetHttpBinding() { MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB, MaxBufferSize = ScenarioTestHelpers.SixtyFourMB, }; binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; binding.MessageEncoding = NetHttpMessageEncoding.Text; binding.WebSocketSettings.KeepAliveInterval = TimeSpan.FromSeconds(2); clientReceiver = new ClientReceiver(); context = new InstanceContext(clientReceiver); channelFactory = new DuplexChannelFactory<IWSDuplexService>(context, binding, new EndpointAddress(Endpoints.WebSocketHttpDuplexTextBuffered_Address)); client = channelFactory.CreateChannel(); // *** EXECUTE *** \\ // Invoking UploadData client.UploadData(ScenarioTestHelpers.CreateInterestingString(123)); // Invoking StartPushingData client.StartPushingData(); Assert.True(clientReceiver.ReceiveDataInvoked.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the buffered response from the Service. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); clientReceiver.ReceiveDataInvoked.Reset(); // Invoking StopPushingData client.StopPushingData(); Assert.True(clientReceiver.ReceiveDataCompleted.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the buffered response from the Service to be completed. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); clientReceiver.ReceiveDataCompleted.Reset(); // Getting results from server via callback. client.GetLog(); Assert.True(clientReceiver.LogReceived.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the Logging from the Service to be received. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); // *** VALIDATE *** \\ Assert.True(clientReceiver.ServerLog.Count > 0, "The logging done by the Server was not returned via the Callback."); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); channelFactory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory); } }
internal static void worker(int loop, string name, InstanceContext context) { //ThreadPool.QueueUserWorkItem(delegate //{ DuplexChannelFactory<ITest> factory = null; ITest channel = null; try { factory = new DuplexChannelFactory<ITest>(context, name); channel = factory.CreateChannel(); using (var scope = new OperationContextScope((IContextChannel)channel)) { OperationContext.Current.OutgoingMessageHeaders.ReplyTo = ((IClientChannel)channel).LocalAddress; // action channel.Ping("Hello, " + loop.ToString()); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(string.Format("[{0}, {1}]: D O N E, tid={2}", loop, name, Thread.CurrentThread.GetHashCode())); Console.ResetColor(); Console.WriteLine("\n+++ press any key to close this channel +++\n"); Console.ReadLine(); } ((IChannel)channel).Close(); factory.Close(); } catch (Exception ex) { if (channel != null) ((IChannel)channel).Abort(); if (factory != null) factory.Abort(); Console.WriteLine(ex.Message); } //}); }
public static void WebSocket_Https_Duplex_TextBuffered_KeepAlive() { #if FULLXUNIT_NOTSUPPORTED bool root_Certificate_Installed = Root_Certificate_Installed(); if (!root_Certificate_Installed) { Console.WriteLine("---- Test SKIPPED --------------"); Console.WriteLine("Attempting to run the test in ToF, a ConditionalFact evaluated as FALSE."); Console.WriteLine("Root_Certificate_Installed evaluated as {0}", root_Certificate_Installed); return; } #endif TextMessageEncodingBindingElement textMessageEncodingBindingElement = null; HttpsTransportBindingElement httpsTransportBindingElement = null; CustomBinding binding = null; ClientReceiver clientReceiver = null; InstanceContext context = null; DuplexChannelFactory<IWSDuplexService> channelFactory = null; IWSDuplexService client = null; try { // *** SETUP *** \\ textMessageEncodingBindingElement = new TextMessageEncodingBindingElement(); httpsTransportBindingElement = new HttpsTransportBindingElement() { MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB, MaxBufferSize = ScenarioTestHelpers.SixtyFourMB }; httpsTransportBindingElement.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; httpsTransportBindingElement.WebSocketSettings.KeepAliveInterval = TimeSpan.FromSeconds(2); binding = new CustomBinding(textMessageEncodingBindingElement, httpsTransportBindingElement); clientReceiver = new ClientReceiver(); context = new InstanceContext(clientReceiver); channelFactory = new DuplexChannelFactory<IWSDuplexService>(context, binding, new EndpointAddress(Endpoints.WebSocketHttpsDuplexTextBuffered_Address)); client = channelFactory.CreateChannel(); // *** EXECUTE *** \\ // Invoking UploadData client.UploadData(ScenarioTestHelpers.CreateInterestingString(123)); // Invoking StartPushingData client.StartPushingData(); Assert.True(clientReceiver.ReceiveDataInvoked.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the buffered response from the Service. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); clientReceiver.ReceiveDataInvoked.Reset(); // Invoking StopPushingData client.StopPushingData(); Assert.True(clientReceiver.ReceiveDataCompleted.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the buffered response from the Service to be completed. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); clientReceiver.ReceiveDataCompleted.Reset(); // Getting results from server via callback. client.GetLog(); Assert.True(clientReceiver.LogReceived.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the Logging from the Service to be received. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); // *** VALIDATE *** \\ Assert.True(clientReceiver.ServerLog.Count > 0, "The logging done by the Server was not returned via the Callback."); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); channelFactory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory); } }
public static void WebSocket_Http_Duplex_BinaryStreamed() { NetHttpBinding binding = null; ClientReceiver clientReceiver = null; InstanceContext context = null; DuplexChannelFactory<IWSDuplexService> channelFactory = null; IWSDuplexService client = null; FlowControlledStream uploadStream = null; try { // *** SETUP *** \\ binding = new NetHttpBinding() { MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB, MaxBufferSize = ScenarioTestHelpers.SixtyFourMB, }; binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; binding.TransferMode = TransferMode.Streamed; binding.MessageEncoding = NetHttpMessageEncoding.Binary; clientReceiver = new ClientReceiver(); context = new InstanceContext(clientReceiver); channelFactory = new DuplexChannelFactory<IWSDuplexService>(context, binding, Endpoints.WebSocketHttpDuplexBinaryStreamed_Address); client = channelFactory.CreateChannel(); // *** EXECUTE *** \\ using (Stream stream = client.DownloadStream()) { int readResult; // Read from the stream, 1000 bytes at a time. byte[] buffer = new byte[1000]; do { readResult = stream.Read(buffer, 0, buffer.Length); } while (readResult != 0); } uploadStream = new FlowControlledStream(); uploadStream.ReadThrottle = TimeSpan.FromMilliseconds(500); uploadStream.StreamDuration = TimeSpan.FromSeconds(1); client.UploadStream(uploadStream); client.StartPushingStream(); // Wait for the callback to get invoked before telling the service to stop streaming. // This ensures we can read from the stream on the callback while the NCL layer at the service // is still writing the bytes from the stream to the wire. // This will deadlock if the transfer mode is buffered because the callback will wait for the // stream, and the NCL layer will continue to buffer the stream until it reaches the end. Assert.True(clientReceiver.ReceiveStreamInvoked.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the stream response from the Service. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); clientReceiver.ReceiveStreamInvoked.Reset(); // Upload the stream while we are downloading a different stream uploadStream = new FlowControlledStream(); uploadStream.ReadThrottle = TimeSpan.FromMilliseconds(500); uploadStream.StreamDuration = TimeSpan.FromSeconds(1); client.UploadStream(uploadStream); client.StopPushingStream(); // Waiting on ReceiveStreamCompleted from the ClientReceiver. Assert.True(clientReceiver.ReceiveStreamCompleted.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the stream response from the Service to be completed. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); clientReceiver.ReceiveStreamCompleted.Reset(); // Getting results from server via callback. client.GetLog(); Assert.True(clientReceiver.LogReceived.WaitOne(ScenarioTestHelpers.TestTimeout), String.Format("Test case timeout was reached while waiting for the Logging from the Service to be received. Timeout was: {0}", ScenarioTestHelpers.TestTimeout)); // *** VALIDATE *** \\ Assert.True(clientReceiver.ServerLog.Count > 0, "The logging done by the Server was not returned via the Callback."); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); channelFactory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory); clientReceiver.Dispose(); } }
public static void WebSocket_WSScheme_WSTransportUsageAlways_DuplexCallback_GuidRoundtrip() { DuplexChannelFactory<IWcfDuplexService> factory = null; IWcfDuplexService proxy = null; Guid guid = Guid.NewGuid(); try { // *** SETUP *** \\ NetHttpBinding binding = new NetHttpBinding(); binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callbackService); UriBuilder builder = new UriBuilder(Endpoints.NetHttpWebSocketTransport_Address); // Replacing "http" with "ws" as the uri scheme. builder.Scheme = "ws"; factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address)); proxy = factory.CreateChannel(); // *** EXECUTE *** \\ Task.Run(() => proxy.Ping(guid)); Guid returnedGuid = callbackService.CallbackGuid; // *** VALIDATE *** \\ Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)proxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)proxy, factory); } }
public static void WebSocket_Http_WSTransportUsageDefault_DuplexCallback_GuidRoundtrip() { DuplexChannelFactory<IWcfDuplexService> factory = null; IWcfDuplexService duplexProxy = null; Guid guid = Guid.NewGuid(); try { // *** SETUP *** \\ NetHttpBinding binding = new NetHttpBinding(); // NetHttpBinding default value of WebSocketTransportSettings.WebSocketTransportUsage is "WhenDuplex" // Therefore using a Duplex Contract will trigger the use of the WCF implementation of WebSockets. WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callbackService); factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpDuplexWebSocket_Address)); duplexProxy = factory.CreateChannel(); // *** EXECUTE *** \\ Task.Run(() => duplexProxy.Ping(guid)); Guid returnedGuid = callbackService.CallbackGuid; // *** VALIDATE *** \\ Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid)); // *** CLEANUP *** \\ ((ICommunicationObject)duplexProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)duplexProxy, factory); } }
static void Main() { _handler += Handler; SetConsoleCtrlHandler(_handler, true); ClientProcessor = new ClientProcessor(); var instanceContext = new InstanceContext(new BombermanCallbackService(ClientProcessor)); Binding binding = new NetTcpBinding(SecurityMode.None); DuplexChannelFactory<IBombermanService> factory = new DuplexChannelFactory<IBombermanService>(instanceContext, binding, new EndpointAddress( new Uri(string.Concat("net.tcp://", ConfigurationManager.AppSettings["MachineName"], ":7900/BombermanCallbackService")))); Proxy = factory.CreateChannel(); Console.WriteLine("--------------------------------------"); Console.WriteLine("-------- Welcome to Bomberman --------"); Console.WriteLine("--------------------------------------\n\n"); do { Console.WriteLine("Type your player name :\n"); Username = Console.ReadLine(); ConnectUser(Username); ClientProcessor.Username = Username; } while (ErrorConnection); Log.Initialize(@"D:\Temp\BombermanLogs", "Client_" + Username + ".log"); Log.WriteLine(Log.LogLevels.Info, "Logged at " + DateTime.Now.ToShortTimeString()); bool stop = false; while (!stop) { ConsoleKeyInfo keyboard = Console.ReadKey(); switch (keyboard.Key) { //s case ConsoleKey.S: StartGame(); break; case ConsoleKey.UpArrow: MoveTo(ActionType.MoveUp); break; case ConsoleKey.LeftArrow: MoveTo(ActionType.MoveLeft); break; case ConsoleKey.RightArrow: MoveTo(ActionType.MoveRight); break; case ConsoleKey.DownArrow: MoveTo(ActionType.MoveDown); break; case ConsoleKey.X: // SinaC: never leave a while(true) without an exit condition stop = true; break; } } // SinaC: Clean properly factory try { factory.Close(); } catch (Exception ex) { Log.WriteLine(Log.LogLevels.Warning, "Exception:{0}", ex); factory.Abort(); } }
// Host the chat instance within this EXE console application. public static void Main() { // Get the memberId from configuration string member = ConfigurationManager.AppSettings["member"]; string issuerName = ConfigurationManager.AppSettings["issuer"]; // Construct InstanceContext to handle messages on callback interface. // An instance of ChatApp is created and passed to the InstanceContext. InstanceContext site = new InstanceContext(new ChatApp()); // Create the participant with the given endpoint configuration // Each participant opens a duplex channel to the mesh // participant is an instance of the chat application that has opened a channel to the mesh DuplexChannelFactory<IChatChannel> cf = new DuplexChannelFactory<IChatChannel>(site, "ChatEndpoint"); X509Certificate2 issuer = GetCertificate(StoreName.TrustedPeople, StoreLocation.CurrentUser, "CN=" + issuerName, X509FindType.FindBySubjectDistinguishedName); cf.Credentials.Peer.Certificate = GetCertificate(StoreName.My, StoreLocation.CurrentUser, "CN=" + member, X509FindType.FindBySubjectDistinguishedName); cf.Credentials.Peer.PeerAuthentication.CertificateValidationMode = X509CertificateValidationMode.Custom; cf.Credentials.Peer.PeerAuthentication.CustomCertificateValidator = new IssuerBasedValidator(issuer); IChatChannel participant = cf.CreateChannel(); // Retrieve the PeerNode associated with the participant and register for online/offline events // PeerNode represents a node in the mesh. Mesh is the named collection of connected nodes. IOnlineStatus ostat = participant.GetProperty<IOnlineStatus>(); ostat.Online += new EventHandler(OnOnline); ostat.Offline += new EventHandler(OnOffline); // Print instructions to user Console.WriteLine("{0} is ready", member); Console.WriteLine("Type chat messages after going Online"); Console.WriteLine("Press q<ENTER> to terminate the application."); // Announce self to other participants participant.Join(member); while (true) { string message = Console.ReadLine(); if (message == "q") break; participant.Chat(member, message); } // Leave the mesh and close the proxy participant.Leave(member); ((IChannel)participant).Close(); cf.Close(); }
public static void CreateChannel_Of_IDuplexChannel_Using_NetTcpBinding_Creates_Unique_Instances() { DuplexChannelFactory<IWcfDuplexService> factory = null; DuplexChannelFactory<IWcfDuplexService> factory2 = null; IWcfDuplexService channel = null; IWcfDuplexService channel2 = null; WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); try { NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); EndpointAddress endpointAddress = new EndpointAddress(FakeAddress.TcpAddress); // Create the channel factory for the request-reply message exchange pattern. factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress); factory2 = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress); // Create the channel. channel = factory.CreateChannel(); Assert.True(typeof(IWcfDuplexService).GetTypeInfo().IsAssignableFrom(channel.GetType().GetTypeInfo()), String.Format("Channel type '{0}' was not assignable to '{1}'", channel.GetType(), typeof(IDuplexChannel))); channel2 = factory2.CreateChannel(); Assert.True(typeof(IWcfDuplexService).GetTypeInfo().IsAssignableFrom(channel2.GetType().GetTypeInfo()), String.Format("Channel type '{0}' was not assignable to '{1}'", channel2.GetType(), typeof(IDuplexChannel))); // Validate ToString() string toStringResult = channel.ToString(); string toStringExpected = "IWcfDuplexService"; Assert.Equal<string>(toStringExpected, toStringResult); // Validate Equals() Assert.StrictEqual<IWcfDuplexService>(channel, channel); // Validate Equals(other channel) negative Assert.NotStrictEqual<IWcfDuplexService>(channel, channel2); // Validate Equals("other") negative Assert.NotStrictEqual<object>(channel, "other"); // Validate Equals(null) negative Assert.NotStrictEqual<IWcfDuplexService>(channel, null); } finally { if (factory != null) { factory.Close(); } if (factory2 != null) { factory2.Close(); } } }
public static void WebSocket_Https_Duplex_TextStreamed() { TextMessageEncodingBindingElement textMessageEncodingBindingElement = null; HttpsTransportBindingElement httpsTransportBindingElement = null; CustomBinding binding = null; ClientReceiver clientReceiver = null; InstanceContext context = null; DuplexChannelFactory<IWSDuplexService> channelFactory = null; IWSDuplexService client = null; FlowControlledStream uploadStream = null; try { // *** SETUP *** \\ textMessageEncodingBindingElement = new TextMessageEncodingBindingElement(); httpsTransportBindingElement = new HttpsTransportBindingElement() { MaxReceivedMessageSize = ScenarioTestHelpers.DefaultMaxReceivedMessageSize, MaxBufferSize = ScenarioTestHelpers.DefaultMaxReceivedMessageSize, TransferMode = TransferMode.Streamed }; httpsTransportBindingElement.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; binding = new CustomBinding(textMessageEncodingBindingElement, httpsTransportBindingElement); clientReceiver = new ClientReceiver(); context = new InstanceContext(clientReceiver); channelFactory = new DuplexChannelFactory<IWSDuplexService>(context, binding, Endpoints.WebSocketHttpsDuplexTextStreamed_Address); client = channelFactory.CreateChannel(); // *** EXECUTE *** \\ using (Stream stream = client.DownloadStream()) { int readResult; // Read from the stream, 1000 bytes at a time. byte[] buffer = new byte[1000]; do { readResult = stream.Read(buffer, 0, buffer.Length); } while (readResult != 0); } uploadStream = new FlowControlledStream(); uploadStream.ReadThrottle = TimeSpan.FromMilliseconds(500); uploadStream.StreamDuration = TimeSpan.FromSeconds(1); client.UploadStream(uploadStream); client.StartPushingStream(); // Wait for the callback to get invoked before telling the service to stop streaming. // This ensures we can read from the stream on the callback while the NCL layer at the service // is still writing the bytes from the stream to the wire. // This will deadlock if the transfer mode is buffered because the callback will wait for the // stream, and the NCL layer will continue to buffer the stream until it reaches the end. Assert.True(clientReceiver.ReceiveStreamInvoked.WaitOne(ScenarioTestHelpers.TestTimeout), "Test case timeout was reached while waiting for the stream response from the Service."); clientReceiver.ReceiveStreamInvoked.Reset(); // Upload the stream while we are downloading a different stream uploadStream = new FlowControlledStream(); uploadStream.ReadThrottle = TimeSpan.FromMilliseconds(500); uploadStream.StreamDuration = TimeSpan.FromSeconds(1); client.UploadStream(uploadStream); client.StopPushingStream(); // Waiting on ReceiveStreamCompleted from the ClientReceiver. Assert.True(clientReceiver.ReceiveStreamCompleted.WaitOne(ScenarioTestHelpers.TestTimeout), "Test case timeout was reached while waiting for the stream response from the Service to be completed."); clientReceiver.ReceiveStreamCompleted.Reset(); // *** VALIDATE *** \\ // Validation is based on no exceptions being thrown. // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); channelFactory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory); clientReceiver.Dispose(); } }
private void Download() { while (!browseFinished) { Thread.Sleep(1000); } logger.Info("Begin to download..."); foreach (var file in downloadFileList) { String relativePath = Path.Combine(syncPath, file.RelativePath); String filePath = Path.Combine(relativePath, file.Name); try { if (File.Exists(filePath)) { File.Delete(filePath); } if (!Directory.Exists(relativePath)) { Directory.CreateDirectory(relativePath); } writer = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write); foreach (var chunkId in file.ChunkList) { var mediaInfo = proxy.DownloadRequest(chunkId); if (mediaInfo == null) { logger.Info("There is no chunk on the media, id: {0}.", chunkId); return; } var tcpAddress = new EndpointAddress("net.tcp://" + mediaInfo.Address + ":" + mediaInfo.Port + "/MediaService"); mediaChannelFactory = new DuplexChannelFactory<IMediaContract>(mediaInstanceContext, tcpBinding, tcpAddress); mediaChannelFactory.Closing += delegate { mediaContract = null; mediaChannelFactory = null; //logger.Debug("Media channel factory is closing..."); }; mediaContract = mediaChannelFactory.CreateChannel(); logger.Debug("Uploading chunking to server, id: {0}", chunkId); mediaContract.DownloadChunk(chunkId); mediaChannelFactory.Close(); } writer.Close(); writer = null; } catch (Exception e) { logger.Error("Failed to download the file, path: {0}.", e); } } }
private void UploadChunk(ChunkInfo chunk) { var mediaInfo = proxy.UploadRequest(chunk.Id); if (mediaInfo == null) { logger.Info("There is the same chunk on the media, id: {0}.", chunk.Id); return; } var tcpAddress = new EndpointAddress("net.tcp://" + mediaInfo.Address + ":" + mediaInfo.Port + "/MediaService"); mediaChannelFactory = new DuplexChannelFactory<IMediaContract>(mediaInstanceContext, tcpBinding, tcpAddress); mediaChannelFactory.Closing += delegate { mediaContract = null; mediaChannelFactory = null; //logger.Debug("Media channel factory is closing..."); }; mediaContract = mediaChannelFactory.CreateChannel(); logger.Debug("Uploading chunking to server, id: {0}, length: {1}.", chunk.Id, chunk.BufferLength); mediaContract.UploadChunk(chunk); mediaChannelFactory.Close(); //writeStream.Write(chunk.Buffer, 0, chunk.BufferLength); }
// Host the chat instance within this EXE console application. public static void Main(string[] args) { Console.WriteLine("Enter your nickname [default=DefaultName]: "); string member = Console.ReadLine(); Console.WriteLine("Enter the mesh password: "******"") member = "DefaultName"; // Construct InstanceContext to handle messages on callback interface. // An instance of ChatApp is created and passed to the InstanceContext. InstanceContext site = new InstanceContext(new ChatApp()); // Create the participant with the given endpoint configuration // Each participant opens a duplex channel to the mesh // participant is an instance of the chat application that has opened a channel to the mesh NetPeerTcpBinding binding = new NetPeerTcpBinding("SecureChatBinding"); ChannelFactory<IChatChannel> cf = new DuplexChannelFactory<IChatChannel>(site, "SecureChatEndpoint"); //for PeerAuthenticationMode.Password, you need to specify a password cf.Credentials.Peer.MeshPassword = password; IChatChannel participant = cf.CreateChannel(); // Retrieve the PeerNode associated with the participant and register for online/offline events // PeerNode represents a node in the mesh. Mesh is the named collection of connected nodes. IOnlineStatus ostat = participant.GetProperty<IOnlineStatus>(); ostat.Online += new EventHandler(OnOnline); ostat.Offline += new EventHandler(OnOffline); // Print instructions to user Console.WriteLine("{0} is ready", member); Console.WriteLine("Type chat messages after going Online"); Console.WriteLine("Press q<ENTER> to terminate this instance."); // Announce self to other participants participant.Join(member); while (true) { string line = Console.ReadLine(); if (line == "q") break; participant.Chat(member, line); } // Leave the mesh and close the proxy participant.Leave(member); ((IChannel)participant).Close(); cf.Close(); }
// Host the chat instance within this EXE console application. public static void Main() { Console.WriteLine("Enter your nickname [default=DefaultName]: "); string member = Console.ReadLine(); if (member == "") member = "DefaultName"; // Construct InstanceContext to handle messages on callback interface. // An instance of ChatApp is created and passed to the InstanceContext. InstanceContext instanceContext = new InstanceContext(new ChatApp(member)); // Create the participant with the given endpoint configuration // Each participant opens a duplex channel to the mesh // participant is an instance of the chat application that has opened a channel to the mesh DuplexChannelFactory<IChatChannel> factory = new DuplexChannelFactory<IChatChannel>(instanceContext, "ChatEndpoint"); IChatChannel participant = factory.CreateChannel(); // Retrieve the PeerNode associated with the participant and register for online/offline events // PeerNode represents a node in the mesh. Mesh is the named collection of connected nodes. IOnlineStatus ostat = participant.GetProperty<IOnlineStatus>(); ostat.Online += new EventHandler(OnOnline); ostat.Offline += new EventHandler(OnOffline); try { participant.Open(); } catch (CommunicationException) { Console.WriteLine("Could not find resolver. If you are using a custom resolver, please ensure"); Console.WriteLine("that the service is running before executing this sample. Refer to the readme"); Console.WriteLine("for more details."); return; } Console.WriteLine("{0} is ready", member); Console.WriteLine("Type chat messages after going Online"); Console.WriteLine("Press q<ENTER> to terminate this instance."); // Announce self to other participants participant.Join(member); // loop until the user quits while (true) { string line = Console.ReadLine(); if (line == "q") break; participant.Chat(member, line); } // Leave the mesh participant.Leave(member); participant.Close(); factory.Close(); }