static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(MonitoringServiceLibrary.MonitoringService)); NetTcpSecurity security = new NetTcpSecurity() { Mode = SecurityMode.None }; NetTcpBinding binding = new NetTcpBinding() { Security = security }; #if DEBUG host.AddServiceEndpoint(typeof(MonitoringServiceLibrary.IMonitoringService), binding, "net.tcp://localhost:9000/MonitoringService"); #endif #if RELEASE host.AddServiceEndpoint(typeof(MonitoringServiceLibrary.IMonitoringService), binding, Properties.Settings.Default.MonitoringServiceUrl); #endif //ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); //host.Description.Behaviors.Add(behavior); //Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding(); //string mexAddress = "net.tcp://localhost:9000/mex"; //host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, mexAddress); host.Open(); Console.WriteLine("Service Started Successfully."); Console.ReadKey(); }
public static void SetBindingSecurity(NetTcpSecurity security) { security.Mode = SecurityMode.Transport; security.Message.ClientCredentialType = MessageCredentialType.Windows; security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign; }
public static void Mode_Property_Sets(SecurityMode mode) { NetTcpSecurity security = new NetTcpSecurity(); security.Mode = mode; Assert.Equal <SecurityMode>(mode, security.Mode); }
public static void Ctor_Default_Initializes_Properties() { // new NetTcpSecurity() initializes correct defaults NetTcpSecurity security = new NetTcpSecurity(); Assert.Equal <SecurityMode>(SecurityMode.Transport, security.Mode); }
public static void Security_Property_Sets() { NetTcpBinding binding = new NetTcpBinding(); NetTcpSecurity security = new NetTcpSecurity(); binding.Security = security; Assert.Equal <NetTcpSecurity>(security, binding.Security); }
static void Main(string[] args) { BinaryFormatter bFormatter = new BinaryFormatter(); FileStream inPut = new FileStream("C:\\Users\\DEVELOPER4\\Desktop\\savefile\\lolblackjagged.yup", FileMode.Open, FileAccess.Read); States state = new States(); state.gridSize = (Size)bFormatter.Deserialize(inPut); state.innerRectColor = (Color[][])bFormatter.Deserialize(inPut); state.innerShapeColor = (Color[][])bFormatter.Deserialize(inPut); state.rectColor = (Color[][])bFormatter.Deserialize(inPut); state.shapeColor = (Color[][])bFormatter.Deserialize(inPut); state.types = (int[][])bFormatter.Deserialize(inPut); state.rotation = (int[][])bFormatter.Deserialize(inPut); state.values = (int[][])bFormatter.Deserialize(inPut); state.circleGrid = (Rectangle[][])bFormatter.Deserialize(inPut); state.rectangleGrid = (Rectangle[][])bFormatter.Deserialize(inPut); state.lvls = Converter.ToJagged(new int[state.gridSize.Height, state.gridSize.Width]); state.owned = new List <Location> [4]; for (int i = 0; i < state.owned.Length; i++) { state.owned[i] = new List <Location>(); } inPut.Close(); Console.WriteLine("Number of Players?"); state.numOfPlayers = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Total Value?"); state.totalValue = Convert.ToInt32(Console.ReadLine()); //ICommandBoardService proxy; using (ServiceHost host = new ServiceHost(typeof(CommandBoardServiceLibrary.CommandBoardService))) { NetTcpBinding ntb = new NetTcpBinding(); NetTcpSecurity nts = new NetTcpSecurity(); nts.Mode = SecurityMode.None; ntb.Security = nts; host.AddServiceEndpoint(typeof( CommandBoardServiceLibrary.ICommandBoardService), new NetTcpBinding(), "net.tcp://localhost:9000/commandboard"); host.Open(); ICommandBoardService proxy = ChannelFactory <ICommandBoardService> .CreateChannel( new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/commandboard")); proxy.setState(state); Console.WriteLine("Good to go"); Console.ReadLine(); } }
public static void Transport_Property_Sets() { NetTcpSecurity security = new NetTcpSecurity(); TcpTransportSecurity newSecurity = new TcpTransportSecurity(); security.Transport = newSecurity; Assert.Equal <TcpTransportSecurity>(newSecurity, security.Transport); }
internal void ApplyConfiguration(NetTcpSecurity security) { if (security == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("security"); } security.Mode = this.Mode; this.Transport.ApplyConfiguration(security.Transport); this.Message.ApplyConfiguration(security.Message); }
internal void InitializeFrom(NetTcpSecurity security) { if (security == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("security"); } SetPropertyValueIfNotDefaultValue(ConfigurationStrings.Mode, security.Mode); this.Transport.InitializeFrom(security.Transport); this.Message.InitializeFrom(security.Message); }
internal void InitializeFrom(NetTcpSecurity security) { if (security == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("security"); } this.Mode = security.Mode; this.Transport.InitializeFrom(security.Transport); this.Message.InitializeFrom(security.Message); }
/// <summary> /// 创建传输协议 /// </summary> /// <param name="binding">传输协议名称</param> /// <returns></returns> private static Binding CreateBinding(string binding) { Binding bindinginstance = null; if (binding.ToLower() == "basichttpbinding") { BasicHttpBinding ws = new BasicHttpBinding(); ws.MaxBufferSize = 2147483647; ws.MaxBufferPoolSize = 2147483647; ws.MaxReceivedMessageSize = 2147483647; ws.ReaderQuotas.MaxStringContentLength = 2147483647; ws.CloseTimeout = new TimeSpan(0, 30, 0); ws.OpenTimeout = new TimeSpan(0, 30, 0); ws.ReceiveTimeout = new TimeSpan(0, 30, 0); ws.SendTimeout = new TimeSpan(0, 30, 0); bindinginstance = ws; } else if (binding.ToLower() == "nettcpbinding") { NetTcpBinding ws = new NetTcpBinding(); ws.MaxReceivedMessageSize = 2147483647; ws.Security.Mode = SecurityMode.None; ws.TransferMode = TransferMode.Streamed; ws.CloseTimeout = new TimeSpan(0, 10, 0); ws.OpenTimeout = new TimeSpan(0, 10, 0); ws.ReceiveTimeout = new TimeSpan(0, 10, 0); ws.SendTimeout = new TimeSpan(0, 10, 0); NetTcpSecurity security = new NetTcpSecurity(); security.Mode = SecurityMode.None; security.Transport = new TcpTransportSecurity() { ClientCredentialType = TcpClientCredentialType.None }; ws.Security = security; ws.ReliableSession = new OptionalReliableSession() { InactivityTimeout = new TimeSpan(0, 10, 0) }; bindinginstance = ws; } else if (binding.ToLower() == "wshttpbinding") { WSHttpBinding ws = new WSHttpBinding(SecurityMode.None); ws.MaxReceivedMessageSize = 65535000; ws.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.Windows; ws.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows; bindinginstance = ws; } return(bindinginstance); }
private static NetTcpBinding getTcpBinding() { #region NetTcpBinding tcpbinding = new NetTcpBinding(); NetTcpSecurity security = new NetTcpSecurity(); security.Mode = SecurityMode.None; tcpbinding.Security = security; tcpbinding.MaxBufferSize = 2147483647; tcpbinding.MaxReceivedMessageSize = 2147483647; return(tcpbinding); #endregion }
public void Connect(User p) { OptionalReliableSession OptionalReliableSession = new OptionalReliableSession { Enabled = true, InactivityTimeout = TimeSpan.MaxValue, Ordered = true }; NetTcpSecurity netTcpSecurity = new NetTcpSecurity { Mode = SecurityMode.None }; XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas { MaxDepth = 32 * 2, MaxStringContentLength = 8192 * 2, MaxArrayLength = 16384 * 2, MaxBytesPerRead = 4096 * 2, MaxNameTableCharCount = 16384 * 2 }; NetTcpBinding netTcpBinding = new NetTcpBinding { Name = "DuplexBinding", ReceiveTimeout = TimeSpan.FromMinutes(10 * 2), ReliableSession = OptionalReliableSession, Security = netTcpSecurity, CloseTimeout = TimeSpan.FromMinutes(2), SendTimeout = TimeSpan.FromMinutes(2), OpenTimeout = TimeSpan.FromMinutes(2), ReaderQuotas = readerQuotas, MaxBufferPoolSize = 524288 * 2, MaxReceivedMessageSize = 65536 * 2, HostNameComparisonMode = HostNameComparisonMode.StrongWildcard, ListenBacklog = 10 * 2, MaxBufferSize = 65536 * 2, MaxConnections = 48 * 2, TransactionFlow = false, TransferMode = TransferMode.Buffered, PortSharingEnabled = false, Namespace = "http://tempuri.org/" }; InstanceContext site = new InstanceContext(this); proxy = new ChatProxy(site, netTcpBinding, new EndpointAddress(Uri)); IAsyncResult iar = proxy.BeginJoin(p, new AsyncCallback(OnEndJoin), null); }
public static void Snippet2() { using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService))) { serviceHost.Open(); ServiceEndpointCollection endpoints = serviceHost.Description.Endpoints; ServiceEndpoint endpoint = endpoints.Find(typeof(ICalculator)); NetTcpBinding binding = (NetTcpBinding)endpoint.Binding; // <Snippet2> NetTcpSecurity security = binding.Security; Console.WriteLine("\tSecurity Mode: {0}", security.Mode); // </Snippet2> } }
public static void Main() { // <Snippet0> using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService))) { serviceHost.Open(); ServiceEndpointCollection endpoints = serviceHost.Description.Endpoints; ServiceEndpoint endpoint = endpoints.Find(typeof(ICalculator)); NetTcpBinding binding = (NetTcpBinding)endpoint.Binding; // <Snippet1> NetTcpSecurity security = binding.Security; MessageSecurityOverTcp msTcp = security.Message; Console.WriteLine("Dumping NetTcpSecurity object:"); Console.WriteLine("\tMessageSecurityOverTcp:"); Console.WriteLine("\t\tAlgorithm Suite: {0}", msTcp.AlgorithmSuite); Console.WriteLine("\t\tClient Credential Type: {0}", msTcp.ClientCredentialType); // </Snippet1> Console.WriteLine("\tSecurity Mode: {0}", security.Mode); // <Snippet3> TcpTransportSecurity tsTcp = security.Transport; Console.WriteLine("\tTcpTransportSecurity:"); Console.WriteLine("\t\tClient Credential Type: {0}", tsTcp.ClientCredentialType); Console.WriteLine("\t\tProtectionLevel: {0}", tsTcp.ProtectionLevel); // </Snippet3> // The service can now be accessed. Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); } // </Snippet0> }
public static List <NetTcpBinding> GetNetTcpBindings(string exeConfigPath) { if (string.IsNullOrWhiteSpace(exeConfigPath)) { return(null); } var svcSection = Read.Config.ExeConfig.GetServiceModelSection(exeConfigPath); var defaultTimeout = new TimeSpan(0, 0, 60); var configs = new List <NetTcpBinding>(); foreach ( var section in svcSection.Bindings.NetTcpBinding.ConfiguredBindings .Cast <NetTcpBindingElement>()) { var dfltb = new NetTcpBinding(); var binding = new NetTcpBinding { Name = section.Name, CloseTimeout = section.CloseTimeout != TimeSpan.Zero ? section.CloseTimeout : defaultTimeout, OpenTimeout = section.OpenTimeout != TimeSpan.Zero ? section.OpenTimeout : defaultTimeout, SendTimeout = section.SendTimeout != TimeSpan.Zero ? section.SendTimeout : defaultTimeout, ReceiveTimeout = section.ReceiveTimeout != TimeSpan.Zero ? section.ReceiveTimeout : defaultTimeout, MaxReceivedMessageSize = section.MaxReceivedMessageSize > 0 ? section.MaxReceivedMessageSize : dfltb.MaxReceivedMessageSize, MaxBufferPoolSize = section.MaxBufferPoolSize > 0 ? section.MaxBufferPoolSize : dfltb.MaxBufferPoolSize, MaxConnections = section.MaxConnections > 0 ? section.MaxConnections : dfltb.MaxConnections, ListenBacklog = section.ListenBacklog > 0 ? section.ListenBacklog : dfltb.ListenBacklog, PortSharingEnabled = section.PortSharingEnabled, TransactionFlow = section.TransactionFlow, TransferMode = section.TransferMode, HostNameComparisonMode = section.HostNameComparisonMode }; var readerQuotasSection = section.ReaderQuotas; var readerQuotas = new System.Xml.XmlDictionaryReaderQuotas(); if (readerQuotasSection != null && readerQuotasSection.MaxDepth > 0) { readerQuotas.MaxDepth = readerQuotasSection.MaxDepth; readerQuotas.MaxStringContentLength = readerQuotasSection.MaxStringContentLength; readerQuotas.MaxArrayLength = readerQuotasSection.MaxArrayLength; readerQuotas.MaxBytesPerRead = readerQuotasSection.MaxBytesPerRead; readerQuotas.MaxNameTableCharCount = readerQuotasSection.MaxNameTableCharCount; } else { readerQuotas = null; } var netTcpSecurity = new NetTcpSecurity { Mode = section.Security.Mode }; var tcpTransportSecurity = new TcpTransportSecurity(); var msgSecurityOverTcp = new MessageSecurityOverTcp { ClientCredentialType = section.Security.Message.ClientCredentialType, AlgorithmSuite = section.Security.Message.AlgorithmSuite }; netTcpSecurity.Message = msgSecurityOverTcp; netTcpSecurity.Transport = tcpTransportSecurity; binding.Security = netTcpSecurity; if (readerQuotas != null) { binding.ReaderQuotas = readerQuotas; } binding.ReliableSession = new OptionalReliableSession { Enabled = section.ReliableSession.Enabled, InactivityTimeout = section.ReliableSession.InactivityTimeout, Ordered = section.ReliableSession.Ordered }; configs.Add(binding); } return(configs); }
public void Connect(string addr, int port) { tracer.Verb("ScreenCastControl::Connecting(...) " + addr + " " + port); hWnd = this.Handle;//this.Parent.Parent.Handle; //logger.Debug("RemoteDesktopClient::Connecting(...) " + addr + " " + port); state = ClientState.Connecting; cancelled = false; errorCode = ErrorCode.Ok; this.ServerAddr = addr; this.ServerPort = port; this.ClientId = RngProvider.GetRandomNumber().ToString(); var address = "net.tcp://" + ServerAddr + "/ScreenCaster"; if (this.ServerPort > 0) { address = "net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster"; } //Console.WriteLine(address); UpdateControls(); mainTask = Task.Run(() => { //int maxTryCount = 10; uint tryCount = 0; bool forceReconnect = (MaxTryConnectCount == uint.MaxValue); while ((forceReconnect || tryCount <= MaxTryConnectCount) && !cancelled) { tracer.Verb("ScreenCastControl::Connecting count: " + tryCount); //logger.Debug("Connecting count: " + tryCount); //errorMessage = ""; errorCode = ErrorCode.Ok; try { var uri = new Uri(address); NetTcpSecurity security = new NetTcpSecurity { Mode = SecurityMode.None, }; var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), SendTimeout = TimeSpan.FromSeconds(5), OpenTimeout = TimeSpan.FromSeconds(5), Security = security, }; //var _uri = new Uri("net.tcp://" + ServerAddr + ":" + 0 + "/ScreenCaster"); //factory = new ChannelFactory<IScreenCastService>(binding, new EndpointAddress(_uri)); //var viaUri = new Uri("net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster"); //factory.Endpoint.EndpointBehaviors.Add(new System.ServiceModel.Description.ClientViaBehavior(viaUri)); factory = new ChannelFactory <IScreenCastService>(binding, new EndpointAddress(uri)); factory.Closed += Factory_Closed; var channel = factory.CreateChannel(); try { var channelInfos = channel.GetChannelInfos(); state = ClientState.Connected; UpdateControls(); Connected?.Invoke(); if (channelInfos == null) { errorCode = ErrorCode.NotReady; throw new Exception("Server not configured"); } var videoChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is VideoChannelInfo); if (videoChannelInfo != null) { if (videoChannelInfo.Transport == TransportMode.Tcp && videoChannelInfo.ClientsCount > 0) { errorCode = ErrorCode.IsBusy; throw new Exception("Server is busy"); } SetupVideo(videoChannelInfo); } var audioChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is AudioChannelInfo); if (audioChannelInfo != null) { if (audioChannelInfo.Transport == TransportMode.Tcp && videoChannelInfo.ClientsCount > 0) { errorCode = ErrorCode.IsBusy; throw new Exception("Server is busy"); } SetupAudio(audioChannelInfo); } if (VideoReceiver != null) { VideoReceiver.Play(); // d3dRenderer.Start(); } if (AudioReceiver != null) { AudioReceiver.Play(); } channel.PostMessage(new ServerRequest { Command = "Ping" }); tryCount = 0; state = ClientState.Running; UpdateControls(); while (state == ClientState.Running) { try { channel.PostMessage(new ServerRequest { Command = "Ping" }); if (d3dRenderer.ErrorCode != 0) { tracer.Warn("ScreenCastControl::imageProvider.ErrorCode: " + d3dRenderer.ErrorCode); // logger.Debug("imageProvider.ErrorCode: " + videoRenderer.ErrorCode); //Process render error... } //TODO:: // Receivers errors... syncEvent.WaitOne(1000); } catch (Exception ex) { state = ClientState.Interrupted; errorCode = ErrorCode.Interrupted; } } } finally { CloseChannel(channel); } } catch (EndpointNotFoundException ex) { errorCode = ErrorCode.NotFound; tracer.Error(ex.Message); //logger.Error(ex.Message); //Console.WriteLine(ex.Message); } catch (Exception ex) { tracer.Error(ex); //logger.Error(ex); if (errorCode == ErrorCode.Ok) { errorCode = ErrorCode.Fail; } //Console.WriteLine(ex); } finally { Close(); } if (!cancelled) { if (errorCode != ErrorCode.Ok) { UpdateControls(); tryCount++; var statusStr = "Attempting to connect..."; // + tryCount; // + " of " + maxTryCount; SetStatus(statusStr); } Thread.Sleep(1000); continue; } else { errorCode = ErrorCode.Cancelled; break; } }//while end cancelled = false; state = ClientState.Disconnected; UpdateControls(); Disconnected?.Invoke(null); }); }
bool ImportNetTcpBinding( WsdlImporter importer, WsdlEndpointConversionContext context, CustomBinding custom, WS.Soap12Binding soap) { TcpTransportBindingElement transportElement = null; BinaryMessageEncodingBindingElement binaryElement = null; TransactionFlowBindingElement transactionFlowElement = null; WindowsStreamSecurityBindingElement windowsStreamElement = null; SslStreamSecurityBindingElement sslStreamElement = null; bool foundUnknownElement = false; foreach (var element in custom.Elements) { if (element is TcpTransportBindingElement) { transportElement = (TcpTransportBindingElement)element; } else if (element is BinaryMessageEncodingBindingElement) { binaryElement = (BinaryMessageEncodingBindingElement)element; } else if (element is TransactionFlowBindingElement) { transactionFlowElement = (TransactionFlowBindingElement)element; } else if (element is WindowsStreamSecurityBindingElement) { windowsStreamElement = (WindowsStreamSecurityBindingElement)element; } else if (element is SslStreamSecurityBindingElement) { sslStreamElement = (SslStreamSecurityBindingElement)element; } else { importer.AddWarning( "Found unknown binding element `{0}' while importing " + "binding `{1}'.", element.GetType(), custom.Name); foundUnknownElement = true; } } if (foundUnknownElement) { return(false); } if (transportElement == null) { importer.AddWarning( "Missing TcpTransportBindingElement while importing " + "binding `{0}'.", custom.Name); return(false); } if (binaryElement == null) { importer.AddWarning( "Missing BinaryMessageEncodingBindingElement while importing " + "binding `{0}'.", custom.Name); return(false); } if ((windowsStreamElement != null) && (sslStreamElement != null)) { importer.AddWarning( "Found both WindowsStreamSecurityBindingElement and " + "SslStreamSecurityBindingElement while importing binding `{0}.", custom.Name); return(false); } NetTcpSecurity security; if (windowsStreamElement != null) { security = new NetTcpSecurity(SecurityMode.Transport); security.Transport.ProtectionLevel = windowsStreamElement.ProtectionLevel; } else if (sslStreamElement != null) { security = new NetTcpSecurity(SecurityMode.TransportWithMessageCredential); } else { security = new NetTcpSecurity(SecurityMode.None); } var netTcp = new NetTcpBinding(transportElement, security, false); netTcp.Name = context.Endpoint.Binding.Name; netTcp.Namespace = context.Endpoint.Binding.Namespace; context.Endpoint.Binding = netTcp; return(true); }
public static void Mode_Property_Set_Invalid_Value_Throws() { NetTcpSecurity security = new NetTcpSecurity(); Assert.Throws <ArgumentOutOfRangeException>(() => security.Mode = (SecurityMode)999); }
private void ClientProc() { var address = "net.tcp://" + ServerAddr + "/RemoteDesktop"; try { var uri = new Uri(address); //NetTcpSecurity security = new NetTcpSecurity //{ // Mode = SecurityMode.Transport, // Transport = new TcpTransportSecurity // { // ClientCredentialType = TcpClientCredentialType.Windows, // ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign, // }, //}; NetTcpSecurity security = new NetTcpSecurity { Mode = SecurityMode.None, }; var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), SendTimeout = TimeSpan.FromSeconds(10), Security = security, }; factory = new ChannelFactory <IRemoteDesktopService>(binding, new EndpointAddress(uri)); var channel = factory.CreateChannel(); try { this.ClientId = RngProvider.GetRandomNumber().ToString(); var connectReq = new RemoteDesktopRequest { SenderId = ClientId, }; var connectionResponse = channel.Connect(connectReq); if (!connectionResponse.IsSuccess) { logger.Error("connectionResponse " + connectionResponse.FaultCode); return; } this.ServerId = connectionResponse.ServerId; this.ServerName = connectionResponse.HostName; var screens = connectionResponse.Screens; var primaryScreen = screens.FirstOrDefault(s => s.IsPrimary); var startRequest = new StartSessionRequest { SenderId = this.ClientId, SrcRect = primaryScreen.Bounds, DestAddr = "", //"192.168.1.135",//localAddr.Address.ToString(), //localAddr.ToString(), DestPort = 1234, DstSize = new Size(1920, 1080), EnableInputSimulator = true, }; var startResponse = channel.Start(startRequest); if (!startResponse.IsSuccess) { logger.Error("startResponse " + startResponse.FaultCode); return; } var inputPars = new VideoEncoderSettings { Resolution = startRequest.DstSize, //Width = startRequest.DstSize.Width, //Height = startRequest.DstSize.Height, //Width = 640,//2560, //Height = 480,//1440, FrameRate = 30, }; var outputPars = new VideoEncoderSettings { //Width = 640,//2560, //Height = 480,//1440, //Width = startRequest.DstSize.Width, //Height = startRequest.DstSize.Height, Resolution = startRequest.DstSize, FrameRate = 30, }; var transport = TransportMode.Udp; var networkPars = new NetworkSettings { LocalAddr = ServerAddr, LocalPort = 1234, TransportMode = transport, }; this.Play(inputPars, outputPars, networkPars); InputManager = new InputManager(); InputManager.Start(ServerAddr, 8888); running = true; State = ClientState.Connected; OnStateChanged(State); while (running) { channel.PostMessage("Ping", null); syncEvent.WaitOne(1000); //InternalCommand command = null; //do //{ // command = DequeueCommand(); // if (command != null) // { // ProcessCommand(command); // } //} while (command != null); } } finally { running = false; State = ClientState.Disconnected; OnStateChanged(State); try { var c = (IClientChannel)channel; if (c.State != CommunicationState.Faulted) { c.Close(); } else { c.Abort(); } } catch (Exception ex) { logger.Error(ex); } } } catch (Exception ex) { logger.Error(ex); State = ClientState.Faulted; OnStateChanged(State); Close(); } }
public void Open() { logger.Debug("ScreenCastService::Open(...)"); try { var session = mediaStreamer.Session; var videoSettings = session.VideoSettings; var videoDeviceName = videoSettings.CaptureDevice?.Name ?? ""; var hostName = session.StreamName; if (!string.IsNullOrEmpty(videoDeviceName)) { hostName += " (" + videoDeviceName + ")"; } var audioSettings = session.AudioSettings; var audioDeviceName = audioSettings.CaptureDevice?.Name ?? ""; var communicationPort = session.CommunicationPort; if (communicationPort < 0) { communicationPort = 0; } if (communicationPort == 0) {// FIXME: переделать // если порт не задан - ищем свободный начиная с 808 //communicationPort = GetRandomTcpPort(); var freeTcpPorts = MediaToolkit.Utils.NetTools.GetFreePortRange(System.Net.Sockets.ProtocolType.Tcp, 1, 808); if (freeTcpPorts != null && freeTcpPorts.Count() > 0) { communicationPort = freeTcpPorts.FirstOrDefault(); } } session.CommunicationPort = communicationPort; var communicationIp = session.NetworkIpAddress; var address = session.CommunicationAddress; this.ListenUri = new Uri(address); this.HostName = hostName; this.ServerId = MediaToolkit.Utils.RngProvider.GetRandomNumber().ToString(); Dictionary <string, string> endpointExtensions = new Dictionary <string, string> {// инфа которая будет доступна как расширение в WSDiscovery { "HostName", HostName }, { "StreamId", ServerId }, { "StreamName", session.StreamName }, { "AudioInfo", audioDeviceName }, { "VideoInfo", videoDeviceName }, }; //NetHttpBinding binding = new NetHttpBinding //{ // ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), // SendTimeout = TimeSpan.FromSeconds(10), //}; //NetTcpSecurity security = new NetTcpSecurity //{ // Mode = SecurityMode.Transport, // Transport = new TcpTransportSecurity // { // ClientCredentialType = TcpClientCredentialType.Windows, // ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign, // }, //}; NetTcpSecurity security = new NetTcpSecurity { Mode = SecurityMode.None, }; var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), SendTimeout = TimeSpan.FromSeconds(10), Security = security, // PortSharingEnabled = true, }; host = new ServiceHost(this, ListenUri); //host = new ServiceHost(this); //var endpoint = host.AddServiceEndpoint(typeof(IScreenCastService), binding, ""); var endpoint = host.AddServiceEndpoint(typeof(IScreenCastService), binding, ListenUri); if (communicationPort == 0) {// сейчас не работает на клиенте !! // нужно доделать клиент endpoint.ListenUriMode = System.ServiceModel.Description.ListenUriMode.Unique; } var endpointDiscoveryBehavior = new EndpointDiscoveryBehavior(); foreach (var key in endpointExtensions.Keys) { var element = new System.Xml.Linq.XElement(key, endpointExtensions[key]); endpointDiscoveryBehavior.Extensions.Add(element); } //var addrInfos = MediaToolkit.Utils.NetworkHelper.GetActiveUnicastIpAddressInfos(); //foreach (var addr in addrInfos) //{ // endpointDiscoveryBehavior.Scopes.Add(new Uri(uri, @"ListenAddr/" + addr.Address)); //} endpoint.EndpointBehaviors.Add(endpointDiscoveryBehavior); ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceDiscoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Description.Behaviors.Add(serviceDiscoveryBehavior); //host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); host.Description.Endpoints.Add(new UdpDiscoveryEndpoint()); host.Opened += Host_Opened; host.Faulted += Host_Faulted; host.Closed += Host_Closed; host.Open(); foreach (var dispatcher in host.ChannelDispatchers) { var listener = dispatcher.Listener; if (listener != null) { var uri = listener.Uri; if (uri != null) { var _host = uri.Host; if (_host == session.NetworkIpAddress) { //получаем порт на котором работает служба // если порт задан динамически session.CommunicationPort = uri.Port; } logger.Info(uri); } } } logger.Debug("Service opened: " + ListenUri.ToString()); } catch (Exception ex) { logger.Error(ex); Close(); var caption = "Network Error"; var message = "Network host opening error. Check network port and other settings."; throw new StreamerException(message, caption); } }
private void TcpTransportCert() { // This string uses a function to prepend the computer name at run time. string addressTCP = String.Format( "net.tcp://{0}:8036/NetTcpSecurity/Transport/Certificate", System.Net.Dns.GetHostEntry("").HostName); // <Snippet1> NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate; // </Snippet1> // <Snippet3> NetTcpBinding bSecurity = new NetTcpBinding(SecurityMode.Transport); // </Snippet3> // <Snippet4> NetTcpBinding bConfigurationName = new NetTcpBinding("MyConfiguration"); // </Snippet4> // <Snippet5> NetTcpBinding bSecurityReliable = new NetTcpBinding(SecurityMode.Transport, true); // </Snippet5> // <Snippet6> EnvelopeVersion envelopeVersion = binding.EnvelopeVersion; // </Snippet6> // <Snippet7> HostNameComparisonMode hostNameComparisonMode = binding.HostNameComparisonMode; // </Snippet7> // <Snippet8> int listenBacklog = binding.ListenBacklog; // </Snippet8> // <Snippet9> long maxBufferPoolsize = binding.MaxBufferPoolSize; // </Snippet9> // <Snippet10> int maxBufferSize = binding.MaxBufferSize; // </Snippet10> // <Snippet11> int maxConnections = binding.MaxConnections; // </Snippet11> // <Snippet12> long MaxReceivedMessageSize = binding.MaxReceivedMessageSize; // </Snippet12> // <Snippet13> bool portSharingEnabled = binding.PortSharingEnabled; // </Snippet13> // <Snippet14> XmlDictionaryReaderQuotas xmlDictionaryReaderQuotas = binding.ReaderQuotas; // </Snippet14> // <Snippet15> OptionalReliableSession reliableSession = binding.ReliableSession; // </Snippet15> // <Snippet16> string scheme = binding.Scheme; // </Snippet16> // <Snippet17> NetTcpSecurity security = binding.Security; // </Snippet17> // <Snippet18> bool transactionFlow = binding.TransactionFlow; // </Snippet18> // <Snippet19> TransactionProtocol transactionProtocol = binding.TransactionProtocol; // </Snippet19> // <Snippet20> BindingElementCollection elementCollection = binding.CreateBindingElements(); // </Snippet20> // <Snippet21> // P:System.ServiceModel.NetTcpBinding.System.ServiceModel.Channels. // IBindingRuntimePreferences.ReceiveSynchronously // Private, no example needed // </Snippet21> // <Snippet22> TransferMode transferMode = binding.TransferMode; // </Snippet22> // You must create an array of URI objects to have a base address. Uri a = new Uri(addressTCP); Uri[] baseAddresses = new Uri[] { a }; // Create the ServiceHost. The service type (Calculator) is not // shown here. ServiceHost sh = new ServiceHost(typeof(Calculator), baseAddresses); // Add an endpoint to the service. Insert the thumbprint of an X.509 // certificate found on your computer. Type c = typeof(ICalculator); //sh.AddServiceEndpoint(c, b, "Aloha"); sh.Credentials.ServiceCertificate.SetCertificate( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "af1f51b25cd413ed9cd00c315bbb6dc1c08da5e6"); // This next line is optional. It specifies that the client's certificate // does not have to be issued by a trusted authority, but can be issued // by a peer if it is in the Trusted People store. Do not use this setting // for production code. // sh.Credentials.ClientCertificate.Authentication.CertificateValidationMode = //X509CertificateValidationMode.PeerOrChainTrust; sh.Open(); string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; Console.WriteLine("Listening @ {0}", address); Console.WriteLine("Press enter to close the service"); Console.ReadLine(); }
private void ClientProc() { var address = "net.tcp://" + ServerAddr + "/ScreenCaster"; if (this.ServerPort > 0) { address = "net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster"; } try { var uri = new Uri(address); this.ClientId = RngProvider.GetRandomNumber().ToString(); //NetTcpSecurity security = new NetTcpSecurity //{ // Mode = SecurityMode.Transport, // Transport = new TcpTransportSecurity // { // ClientCredentialType = TcpClientCredentialType.Windows, // ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign, // }, //}; NetTcpSecurity security = new NetTcpSecurity { Mode = SecurityMode.None, }; var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), SendTimeout = TimeSpan.FromSeconds(10), Security = security, }; factory = new ChannelFactory<IScreenCastService>(binding, new EndpointAddress(uri)); var channel = factory.CreateChannel(); try { //channel.PostMessage(new ServerRequest { Command = "Ping" }); var channelInfos = channel.GetChannelInfos(); if (channelInfos == null) { logger.Error("channelInfos == null"); return; } TransportMode transportMode = TransportMode.Udp; var videoChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is VideoChannelInfo); if (videoChannelInfo != null) { transportMode = videoChannelInfo.Transport; if(transportMode == TransportMode.Tcp) { if (videoChannelInfo.ClientsCount > 0) { throw new Exception("Server is busy"); } } var videoAddr = videoChannelInfo.Address; if(transportMode == TransportMode.Tcp) { videoAddr = ServerAddr; } var videoPort = videoChannelInfo.Port; //if (string.IsNullOrEmpty(videoAddr)) //{ // //channel.Play() //} //if (transportMode == TransportMode.Tcp) //{ // var res = channel.Play(channelInfos); //} var videoInfo = videoChannelInfo.MediaInfo as VideoChannelInfo; if (videoInfo != null) { var inputPars = new VideoEncoderSettings { Resolution = videoInfo.Resolution, //Width = videoInfo.Resolution.Width, //Height = videoInfo.Resolution.Height, FrameRate = new MediaRatio(videoInfo.Fps, }; var outputPars = new VideoEncoderSettings { //Width = 640,//2560, //Height = 480,//1440, //Width = 1920, //Height = 1080, //FrameRate = 30, //Width = videoInfo.Resolution.Width, //Height = videoInfo.Resolution.Height, Resolution = videoInfo.Resolution, FrameRate = videoInfo.Fps, }; //bool keepRatio = true; //if (keepRatio) //{ // var srcSize = new Size(inputPars.Width, inputPars.Height); // var destSize = new Size(outputPars.Width, outputPars.Height); // var ratio = srcSize.Width / (double)srcSize.Height; // int destWidth = destSize.Width; // int destHeight = (int)(destWidth / ratio); // if (ratio < 1) // { // destHeight = destSize.Height; // destWidth = (int)(destHeight * ratio); // } // outputPars.Width = destWidth; // outputPars.Height = destHeight; //} var networkPars = new NetworkSettings { LocalAddr = videoAddr, LocalPort = videoPort, TransportMode = transportMode, SSRC = videoChannelInfo.SSRC, }; VideoReceiver = new VideoReceiver(); VideoReceiver.Setup(inputPars, outputPars, networkPars); VideoReceiver.UpdateBuffer += VideoReceiver_UpdateBuffer; } } var audioChannelInfo =channelInfos.FirstOrDefault(c => c.MediaInfo is AudioChannelInfo); if (audioChannelInfo != null) { var audioInfo = audioChannelInfo.MediaInfo as AudioChannelInfo; if (audioInfo != null) { var audioAddr = audioChannelInfo.Address; transportMode = audioChannelInfo.Transport; if (transportMode == TransportMode.Tcp) { audioAddr = ServerAddr; } if (transportMode == TransportMode.Tcp) { if (audioChannelInfo.ClientsCount > 0) { throw new Exception("Server is busy"); } } var audioPort = audioChannelInfo.Port; AudioReceiver = new AudioReceiver(); var networkPars = new NetworkSettings { LocalAddr = audioAddr, LocalPort = audioPort, TransportMode = transportMode, SSRC = audioChannelInfo.SSRC, }; var audioDeviceId = ""; try { var devices = DirectSoundOut.Devices; var device = devices.FirstOrDefault(); audioDeviceId = device?.Guid.ToString() ?? ""; } catch(Exception ex) { logger.Error(ex); } var audioPars = new AudioEncoderSettings { SampleRate = audioInfo.SampleRate, Channels = audioInfo.Channels, Encoding = "ulaw", DeviceId = audioDeviceId,//currentDirectSoundDeviceInfo?.Guid.ToString() ?? "", }; AudioReceiver.Setup(audioPars, networkPars); } } if (VideoReceiver != null) { VideoReceiver.Play(); } if (AudioReceiver != null) { AudioReceiver.Play(); } running = true; State = ClientState.Connected; OnStateChanged(State); while (running) { channel.PostMessage(new ServerRequest { Command = "Ping" }); syncEvent.WaitOne(1000); //InternalCommand command = null; //do //{ // command = DequeueCommand(); // if (command != null) // { // ProcessCommand(command); // } //} while (command != null); } } finally { running = false; State = ClientState.Disconnected; OnStateChanged(State); try { var c = (IClientChannel)channel; if (c.State != CommunicationState.Faulted) { c.Close(); } else { c.Abort(); } } catch (Exception ex) { logger.Error(ex); } } } catch (Exception ex) { logger.Error(ex); State = ClientState.Faulted; OnStateChanged(State); //Close(); } finally { Close(); } }