static void Main(string[] args) { //Create Client TcpClientChannel channel = new TcpClientChannel(); ChannelServices.RegisterChannel(channel, false); //Get a reference to the player on the server string playerURL = "tcp://localhost:" + 1337 + "/" + "Little"; Player player = (Player)Activator.GetObject(typeof(Player), playerURL); while (true) { Console.Write("Type a message to the server or type 'quit' to exit\n"); string text = Console.ReadLine(); if (text == "quit") { break; } //RPC: Call function on server //extended functionalityVV if (text == "help" || text == "h" || text == "?" || text == "-h" || text == "--h" || text == "-help" || text == "--help") { //list commands //ls //login //quit string[] lsResults = new[] { "----------------------------", "- -", "- COMMANDS -", "- ----- -", "- /ls -", "- /login -", "- /quit -", "- / -", "- -", "----------------------------" }; player.SayHello(lsResults); } if (text == "ls") { //list filesystem string[] fileSystem = new[] { "----------------------------", "- -", "- FILES -", "- ----- -", "- DOCUMENTS -", "- PICTURES -", "- MOVIES -", "- WORK -", "- -", "----------------------------" }; player.SayHello(fileSystem); } if (text == "login") { //list filesystem string[] loginUI = new[] { "----------------------------", "- LOGIN -", "- -", "- USER -", "- ADMIN_ -", "- -", "- PASS -", "- ******_ -", "- -", "----------------------------" }; player.SayHello(loginUI); } } }
private void Packeting() { int iPort = 61100; //read from ini later string sName = "RetroEngineServer"; //read from ini later bool bGood=false; //Script scriptIni; HttpChannel chanRetroEngine=null; //sIni="Server.ini"; bGood=true; if (iPort<1024) { iPort=61100; RReporting.Error_WriteLine(" -Port was reset to "+iPort.ToString()+" because the config file was bad"); } RReporting.Error_WriteLine(" -Port = "+iPort.ToString()); RReporting.Error_WriteLine(" -Server name = "+sName); if (iPort<1024) bGood=false; //debug NYI if not in standard set of allowed (high-number) ports if (bGood) { //Create®ister channel chanRetroEngine = new HttpChannel(iPort); ChannelServices.RegisterChannel(chanRetroEngine); //Register and count server for remoting RemotingConfiguration.RegisterWellKnownServiceType( typeof(Port), sName, WellKnownObjectMode.Singleton); } else { //scriptIni.Dump(); RReporting.Error_WriteLine("The server was not initialized because the port number either set or loaded improperly in initialization file!"); } //if () bContinue=true; Packet packetNow; bool bEmpty=true; while (bContinue) { if (bShuttingDown) { //if (iPacketsSending==0) bContinue=false; //debug this statement should be fixed and used if (PlatformNow.TickCount-iTickShutdown>iTicksToShutdown) bContinue=false; } if (packetqIn!=null) { try { try { bEmpty=packetqIn.IsEmpty; } catch (Exception exn) { RReporting.ShowExn(exn,"Packeting","checking whether packetqIn IsEmpty"); bEmpty=true; } if (!bEmpty) { //Now Run the next Packet packetNow = packetqIn.Deq(); if (packetNow==null) RReporting.ShowErr(" (packetq) packet in non-empty queue was null","Packeting"); else RunPacket(ref packetNow); }//end if not empty } catch (Exception exn) { RReporting.ShowExn(exn,"Packeting","trying to process next incoming packet"); } } else RReporting.ShowErr("packetqIn is not initialized correctly.","Packeting"); } RReporting.WriteLine("Packeting stopped."); //if (tPacketer!=null && tPacketer.IsRunning) tPacketer.Abort(); //is this possible (To exit self)?? //debug }//end Packeting
public bool Connect(string Ip, int Port) { Log.Debug("RpcClient", "Connect : " + Ip + ":" + Port); RpcServerIp = Ip; RpcServerPort = Port; Connecting = true; try { if (Channel != null) { return(false); } Log.Debug("RpcClient", "Connecting to : " + Ip); if (!Pinger.IsAlive) { Pinger.Start(); } Channel = new TcpClientChannel(ServerName, null); ChannelServices.RegisterChannel(Channel, false); Mgr = Activator.GetObject(typeof(ServerMgr), "tcp://" + Ip + ":" + Port + "/" + typeof(ServerMgr).Name) as ServerMgr; Info = Mgr.Connect(ServerName, ServerIp); if (Info == null) { return(false); } Log.Debug("RpcClient", "Listening on : " + ServerIp + ":" + Info.Port); ServerChannel = new TcpServerChannel("Server" + Info.RpcID, Info.Port); ChannelServices.RegisterChannel(ServerChannel, false); RegisteredTypes = RpcObject.RegisterHandlers(false, AllowedID); foreach (Type t in RegisteredTypes[1]) { RpcServer.GetObject(t, Info.Ip, Info.Port).MyInfo = Info; } Mgr.Connected(Info.RpcID); Log.Success("RpcClient", "Connected to : " + ServerIp + ":" + RpcServerPort + ", Listen on : " + Info.Ip + ":" + Info.Port); foreach (Type t in RegisteredTypes[1]) { RpcServer.GetObject(t, Info.Ip, Info.Port).OnServerConnected(); } Connecting = false; } catch (Exception e) { Log.Error("RpcClient", e.ToString()); Log.Notice("RpcClient", "Can not start RPC : " + Ip + ":" + Port); Connecting = false; Mgr = null; Info = null; return(false); } return(true); }
public FileBasedClient(string name) { ChannelServices.RegisterChannel(new FileBasedClientChannel(), false); Name = name; }
private static void InitRemoting() { ChannelServices.RegisterChannel(new IpcChannel(channelName), false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingService), "service.rem", WellKnownObjectMode.Singleton); }
// // Internal // // Transform the ASP+ Request and Response Structures in // Channel Structures: // ** Request.ServerVariables // ** Request.InputStream // ** Response.Headers // // This is needed to reduce the between dependency COR Channels // and ASP+ // private void InternalProcessRequest(HttpContext context) { try { HttpRequest httpRequest = context.Request; // check if have previously loaded configuration if (!bLoadedConfiguration) { // locking a random static variable, so we can lock the class lock (HttpRemotingHandler.ApplicationConfigurationFile) { if (!bLoadedConfiguration) { // Initialize IIS information IisHelper.Initialize(); // set application name if (RemotingConfiguration.ApplicationName == null) { RemotingConfiguration.ApplicationName = httpRequest.ApplicationPath; } String filename = String.Concat(httpRequest.PhysicalApplicationPath, ApplicationConfigurationFile); if (File.Exists(filename)) { try { RemotingConfiguration.Configure(filename); } catch (Exception e) { s_fatalException = e; WriteException(context, e); return; } } try { // do a search for a registered channel that wants to listen IChannelReceiverHook httpChannel = null; IChannel[] channels = ChannelServices.RegisteredChannels; foreach (IChannel channel in channels) { IChannelReceiverHook hook = channel as IChannelReceiverHook; if (hook != null) { if (String.Compare(hook.ChannelScheme, "http", true, CultureInfo.InvariantCulture) == 0) { if (hook.WantsToListen) { httpChannel = hook; break; } } } } if (httpChannel == null) { // No http channel that was listening found. // Create a new channel. HttpChannel newHttpChannel = new HttpChannel(); ChannelServices.RegisterChannel(newHttpChannel); httpChannel = newHttpChannel; } String scheme = null; if (IisHelper.IsSslRequired) { scheme = "https"; } else { scheme = "http"; } String hookChannelUri = scheme + "://" + CoreChannel.GetMachineIp(); int port = context.Request.Url.Port; String restOfUri = ":" + port + "/" + RemotingConfiguration.ApplicationName; hookChannelUri += restOfUri; // add hook uri for this channel httpChannel.AddHookChannelUri(hookChannelUri); // If it uses ChannelDataStore, re-retrieve updated url in case it was updated. ChannelDataStore cds = ((IChannelReceiver)httpChannel).ChannelData as ChannelDataStore; if (cds != null) { hookChannelUri = cds.ChannelUris[0]; } IisHelper.ApplicationUrl = hookChannelUri; // This is a hack to refresh the channel data. // In V-Next, we will add a ChannelServices.RefreshChannelData() api. ChannelServices.UnregisterChannel(null); s_transportSink = new HttpHandlerTransportSink(httpChannel.ChannelSinkChain); } catch (Exception e) { s_fatalException = e; WriteException(context, e); return; } bLoadedConfiguration = true; } } } if (s_fatalException == null) { if (!CanServiceRequest(context)) { WriteException(context, new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"))); } else { s_transportSink.HandleRequest(context); } } else { WriteException(context, s_fatalException); } } catch (Exception e) { WriteException(context, e); } } // InternalProcessRequest
public VisualStudioInstance(Process hostProcess, DTE dte, ImmutableHashSet <string> supportedPackageIds, string installationPath, bool isUsingLspEditor) { HostProcess = hostProcess; Dte = dte; SupportedPackageIds = supportedPackageIds; InstallationPath = installationPath; IsUsingLspEditor = isUsingLspEditor; if (System.Diagnostics.Debugger.IsAttached) { // If a Visual Studio debugger is attached to the test process, attach it to the instance running // integration tests as well. var debuggerHostDte = GetDebuggerHostDte(); var targetProcessId = Process.GetCurrentProcess().Id; var localProcess = debuggerHostDte?.Debugger.LocalProcesses.OfType <EnvDTE80.Process2>().FirstOrDefault(p => p.ProcessID == hostProcess.Id); if (localProcess != null) { localProcess.Attach2("Managed"); } } StartRemoteIntegrationService(dte); _integrationServiceChannel = new IpcClientChannel(GetIpcClientChannelName(HostProcess), sinkProvider: null); ChannelServices.RegisterChannel(_integrationServiceChannel, ensureSecurity: true); // Connect to a 'well defined, shouldn't conflict' IPC channel _integrationService = IntegrationService.GetInstanceFromHostProcess(hostProcess); // Create marshal-by-ref object that runs in host-process. _inProc = ExecuteInHostProcess <VisualStudio_InProc>( type: typeof(VisualStudio_InProc), methodName: nameof(VisualStudio_InProc.Create) ); // There is a lot of VS initialization code that goes on, so we want to wait for that to 'settle' before // we start executing any actual code. _inProc.WaitForSystemIdle(); AddParameterDialog = new AddParameterDialog_OutOfProc(this); ChangeSignatureDialog = new ChangeSignatureDialog_OutOfProc(this); InteractiveWindow = new CSharpInteractiveWindow_OutOfProc(this); ObjectBrowserWindow = new ObjectBrowserWindow_OutOfProc(this); Debugger = new Debugger_OutOfProc(this); Dialog = new Dialog_OutOfProc(this); Editor = new Editor_OutOfProc(this); EncapsulateField = new EncapsulateField_OutOfProc(this); ErrorList = new ErrorList_OutOfProc(this); ExtractInterfaceDialog = new ExtractInterfaceDialog_OutOfProc(this); FindReferencesWindow = new FindReferencesWindow_OutOfProc(this); GenerateTypeDialog = new GenerateTypeDialog_OutOfProc(this); InlineRenameDialog = new InlineRenameDialog_OutOfProc(this); ImmediateWindow = new ImmediateWindow_OutOfProc(this); LocalsWindow = new LocalsWindow_OutOfProc(this); MoveToNamespaceDialog = new MoveToNamespaceDialog_OutOfProc(this); PickMembersDialog = new PickMembersDialog_OutOfProc(this); PreviewChangesDialog = new PreviewChangesDialog_OutOfProc(this); Shell = new Shell_OutOfProc(this); SolutionExplorer = new SolutionExplorer_OutOfProc(this); Workspace = new VisualStudioWorkspace_OutOfProc(this); StartPage = new StartPage_OutOfProc(this); SendKeys = new SendKeys(this); // Ensure we are in a known 'good' state by cleaning up anything changed by the previous instance CleanUp(); }
private static void Sub_Main(string[] orgArgs) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); _logger.Info("\r\n============================================================================\r\nLogExpert {0} started.\r\n============================================================================", Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); CmdLine cmdLine = new CmdLine(); CmdLineString configFile = new CmdLineString("config", false, "A configuration (settings) file"); cmdLine.RegisterParameter(configFile); string[] remainingArgs = cmdLine.Parse(orgArgs); List <string> argsList = new List <string>(); // This loop tries to convert relative file names into absolute file names (assuming that platform file names are given). // It tolerates errors, to give file system plugins (e.g. sftp) a change later. // TODO: possibly should be moved to LocalFileSystem plugin foreach (string fileArg in remainingArgs) { try { FileInfo info = new FileInfo(fileArg); if (info.Exists) { argsList.Add(info.FullName); } else { argsList.Add(fileArg); } } catch (Exception) { argsList.Add(fileArg); } } string[] args = argsList.ToArray(); if (configFile.Exists) { FileInfo cfgFileInfo = new FileInfo(configFile.Value); if (cfgFileInfo.Exists) { ConfigManager.Import(cfgFileInfo, ExportImportFlags.All); } else { MessageBox.Show("Config file not found", "LogExpert"); } } int pId = Process.GetCurrentProcess().SessionId; try { Settings settings = ConfigManager.Settings; bool isCreated = false; Mutex mutex = new System.Threading.Mutex(false, "Local\\LogExpertInstanceMutex" + pId, out isCreated); if (isCreated) { // first application instance Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); LogTabWindow logWin = new LogTabWindow(args.Length > 0 ? args : null, 1, false); // first instance //WindowsIdentity wi = WindowsIdentity.GetCurrent(); IpcServerChannel ipcChannel = new IpcServerChannel("LogExpert" + pId); ChannelServices.RegisterChannel(ipcChannel, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(LogExpertProxy), "LogExpertProxy", WellKnownObjectMode.Singleton); LogExpertProxy proxy = new LogExpertProxy(logWin); RemotingServices.Marshal(proxy, "LogExpertProxy"); LogExpertApplicationContext context = new LogExpertApplicationContext(proxy, logWin); Application.Run(context); ChannelServices.UnregisterChannel(ipcChannel); } else { int counter = 3; Exception errMsg = null; IpcClientChannel ipcChannel = new IpcClientChannel("LogExpertClient#" + pId, null); ChannelServices.RegisterChannel(ipcChannel, false); while (counter > 0) { try { // another instance already exists //WindowsIdentity wi = WindowsIdentity.GetCurrent(); LogExpertProxy proxy = (LogExpertProxy)Activator.GetObject(typeof(LogExpertProxy), "ipc://LogExpert" + pId + "/LogExpertProxy"); if (settings.preferences.allowOnlyOneInstance) { proxy.LoadFiles(args); } else { proxy.NewWindowOrLockedWindow(args); } break; } catch (RemotingException e) { _logger.Warn(e, "IpcClientChannel error: "); errMsg = e; counter--; Thread.Sleep(500); } } if (counter == 0) { _logger.Error(errMsg, "IpcClientChannel error, giving up: "); MessageBox.Show($"Cannot open connection to first instance ({errMsg})", "LogExpert"); } } mutex.Close(); } catch (Exception ex) { _logger.Error(ex, "Mutex error, giving up: "); MessageBox.Show($"Cannot open connection to first instance ({ex.Message})", "LogExpert"); } }
private void StartListening() { IiopChannel channel = null; RtecEventChannelAdmin.ProxyPushSupplier supplier = null; RtecEventComm.PushConsumer consumer = null; try { string host = txtHost.Text; int port = Convert.ToInt32(txtHostPort.Text); m_logger.Log("HostName : " + host); m_logger.Log("Port : " + port.ToString()); IDictionary property = new Hashtable(); channel = new IiopChannel(0); ChannelServices.RegisterChannel(channel, false); CorbaInit init = CorbaInit.GetInit(); NamingContext nameService = (NamingContext)RemotingServices.Connect(typeof(NamingContext), String.Format("corbaloc:iiop:{0}:{1}/NameService", host, port)); RtecEventChannelAdmin.EventChannel ec = ResolveEventChannel(nameService); if (ec != null) { m_logger.Log("Found the EchoEventChannel"); //Obtain a reference to the consumer administration object RtecEventChannelAdmin.ConsumerAdmin admin = ec.for_consumers(); // Obtain a reference to the push supplier proxy. supplier = admin.obtain_push_supplier(); consumer = RegisterConsumer(supplier); m_logger.Log("Ready to Receive Messages..."); this.Run = true; while (this.Run) { Thread.Sleep(1); } } else { m_logger.Log("Not Found the EchoEventChannel"); } } catch (Exception exception) { m_logger.Log(exception.Message); BtnListen.Enabled = true; } finally { if (supplier != null) { supplier.disconnect_push_supplier(); } if (consumer != null) { consumer.disconnect_push_consumer(); RemotingServices.Disconnect((MarshalByRefObject)consumer); } ChannelServices.UnregisterChannel(channel); m_logger.Log("Cleanup event consumer complete."); } }
static void Main(string[] args) { TcpChannel channel; string name; int id; if (args.Count() > 0) { channel = new TcpChannel(Int32.Parse(args[0].Split(':')[2].Split('/')[0])); name = args[0].Split('/')[3]; id = Int32.Parse(args[1]); } else { channel = new TcpChannel(8088); name = "DIDA-TUPLE-SMR"; id = 1; } ChannelServices.RegisterChannel(channel, false); TupleSpaceSMR server = new TupleSpaceSMR(); //Set min delay and max delay if (args.Length == 4) { server.MinDelay = Int32.Parse(args[2]); server.MaxDelay = Int32.Parse(args[3]); } server.MyPath = args[0]; server.ServerId = id; //if requests received, they are delayed until log recover and master finding complete server.SoftFreeze(); RemotingServices.Marshal(server, name, typeof(TupleSpaceSMR)); List <string> servers = new List <string>(); try { string[] file = File.ReadAllLines(Path.Combine(Directory.GetCurrentDirectory(), "../../../config/serverListSMR.txt")); foreach (string i in file) { //Just ignore my path when caching server's URL if (args[0] != i) { servers.Add(i); } } server.SetServers(servers); } catch (FileNotFoundException) { System.Console.WriteLine("Server List not Found"); System.Console.WriteLine("Aborting..."); System.Environment.Exit(1); } string pathMaster = ""; bool logUpdated = false; Console.WriteLine(server.Log); bool alreadyDiscoverMaster = false; for (int i = 0; i < server.ServerId; i++) { foreach (string serverPath in servers) { try { ITotalOrder remoteServer = (ITotalOrder)Activator.GetObject(typeof(ITotalOrder), serverPath); if (logUpdated == false) { //when the server start running fetch from one server the log //so i can sync my tuple space server.Log = remoteServer.fetchLog(); Console.WriteLine(server.Log); //execute by order operation in that log server.executeLog(); logUpdated = true; } //ask if this replic is the master and give them my path if (remoteServer.areYouTheMaster(args[0])) { pathMaster = serverPath; server.MasterPath = pathMaster; //All replicas ping the master server.setBackup(pathMaster); alreadyDiscoverMaster = true; break; } } catch (Exception) { Console.WriteLine((i + 1) + " attempt -> Failed reaching " + serverPath); } } if (alreadyDiscoverMaster) { break; } } //no master exists! so i am the master now! if (pathMaster == "") { server.setIAmTheMaster(); server.MasterPath = server.MyPath; Console.WriteLine("** STATUS: I'm the master now!"); } else { Console.WriteLine("** STATUS: The master is at " + pathMaster); } //log was updated and master search is over, so i can receive client requests server.SoftUnFreeze(); System.Console.WriteLine("DIDA-TUPLE-SMR Server Started!"); System.Console.WriteLine("---------------"); System.Console.WriteLine("<Enter> to exit..."); System.Console.ReadLine(); }
private static void InitRemoting() { ChannelServices.RegisterChannel(new IpcChannel("localhost:62982"), false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProxySwitcher.RemotingService), "ProxySwitcherService.rem", WellKnownObjectMode.Singleton); }
/// <summary> /// Initializes TCP channel and starts remoting server. Should only be called once! /// </summary> private void CreateInterProcessCommunicationServer(int maximumRetries) { ThreadExceptionEventHandler terminator = new ThreadExceptionEventHandler(Application_FatalError); Application.ThreadException += terminator; if (Mode == ExecutionMode.Client) { throw new InvalidOperationException("Server cannot be created in this AppDomain because a client has been created"); } else if (Mode == ExecutionMode.Server) { return; } int retryCount = 0; try { Configuration config = Configuration.GetNewInstance(); while (true) { try { IDictionary properties = new Hashtable(3); properties.Add("bindTo", "127.0.0.1"); properties.Add("port", config.Settings.FrameworkTcpPort); TcpChannel tcpChannel = new TcpChannel(properties, null, null); ChannelServices.RegisterChannel(tcpChannel, false); //chnl.GetUrlsForUri(RemotingUri)[0]; RemotingServices.Marshal(this, GetUniqueRemotingUri(config.ConfigFilePath)); // exit retry while loop break; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); SocketException sex = ex as SocketException; if (sex != null) { // port already in use if (sex.ErrorCode == 10048) { // increment port number and for retry config.Settings.FrameworkTcpPort += 1; Configuration.Save(config); } } if (++retryCount > maximumRetries) { throw; } } } } catch (Exception ex) { throw new GeneralException("Framework interprocess communication initalization failed. Please restart and try again.", ex); } Mode = ExecutionMode.Server; Application.ThreadException -= terminator; // the unhandled exception handler is disabled in debug builds AttachExceptionHandler(); }
public Shell() { chan = new TcpChannel(); ChannelServices.RegisterChannel(chan, false); obj = (SharedObject)Activator.GetObject(typeof(SortLibrary.SharedObject), "tcp://localhost:8081/DataPool"); }
internal ClientImpl() { channel = new HttpChannel(); ChannelServices.RegisterChannel(channel, false); }
private void buttonConnect_Click(object sender, EventArgs e) { try { if (buttonConnect.Text == "Connect") { // Creates a client object that 'lives' here on the client. client = new RemotingClient(); listBoxLog.Items.Add("Created client with ID " + client.ClientID); // Hook into the event exposed on the Sink object so we can transfer a server // message through to this class. client.clientCallback += OnMessageReceived; // Hook into the event to allow the server to send (other) notifications // (Currently only asserted when clients connect or disconnect from server by // means of registering respective event handlers associated with their client // references) client.serverNotificationCallback += OnServerNotification; if (channel == null) { int clientChannel = FindUnusedPort(IPAddress.Loopback); listBoxLog.Items.Add("Using (unused) client port " + clientChannel); if (clientChannel != 0) { BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider(); serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider(); IDictionary props = new Hashtable(); props["port"] = clientChannel; // Register a client channel so the server an communicate back - it needs a channel // opened for the callback to the CallbackSink object that is anchored on the client! // channel = new HttpChannel(clientChannel++); channel = new HttpChannel(props, clientProv, serverProv); } else { throw new Exception("Couldn't find unused client port!"); } } // Registers a channel with the channel services ChannelServices.RegisterChannel(channel, false); // Now create a transparent proxy to the server component MarshalByRefObject obj = (MarshalByRefObject)RemotingServices.Connect(typeof(RemotingServer), "http://" + textBoxServerIPAddress.Text + ":" + textBoxServerPortConnect.Text + "/Server"); server = obj as RemotingServer; // Create messaging callback objects clientCallback = new RemotingClient.ClientCallback(client.SendMessage); // Register callback if (clientCallback != null) { // Simple messaging callback for broadcasting of messages from one client server.RegisterMessageCallback(clientCallback); // Messaging callback associated with the client to allow for sending messages to a particular client server.RegisterMessageCallback(clientCallback, client); } buttonConnect.Text = "Disconnect"; textBoxServerIPAddress.Enabled = false; textBoxServerPortConnect.Enabled = false; foreach (Control control in tabPageServer.Controls) { control.Enabled = false; } } else { if (server != null) { if (clientCallback != null) { server.UnregisterMessageCallback(clientCallback); } if (client != null) { server.UnregisterMessageCallback(client); } } if (client != null) { client.clientCallback -= OnMessageReceived; client.serverNotificationCallback -= OnServerNotification; } if (channel != null) { ChannelDataStore cds = (ChannelDataStore)channel.ChannelData; foreach (string s in cds.ChannelUris) { channel.StopListening(s); } ChannelServices.UnregisterChannel(channel); } clientCallback = null; server = null; client = null; channel = null; OnServerNotification(); buttonConnect.Text = "Connect"; textBoxServerIPAddress.Enabled = true; textBoxServerPortConnect.Enabled = true; foreach (Control control in tabPageServer.Controls) { control.Enabled = true; } } } catch (Exception ex) { listBoxLog.Items.Add(ex.Message); } }
public override void ConfigureClient() { Log(string.Format(Strings.CONFIGURING_CLIENT, GetType().Name, ServerURL), ESeverity.DEBUG); ChannelServices.RegisterChannel(ClientChannel, IsSecured); }
public CnasRemotCall(string strip) { Tcp_connect = strip; ChannelServices.RegisterChannel(new TcpClientChannel(), false); RemotInterface = (CnasHCSInterface)Activator.GetObject(typeof(CnasHCSInterface), Tcp_connect); }
public static bool SetServiceStatusAndStartStyleRemote(string mgtSvcConfigFileName, string serviceName, ServiceStatus status, ILog log) { if (serviceName == null || serviceName.Length < 1) { return(false); } string str = ""; ConfigManager <ServiceConfig> mgt = new ConfigManager <ServiceConfig>(mgtSvcConfigFileName); if (!mgt.Load()) { str = "Load file failed: " + mgt.FileName; if (log != null) { log.Write(LogType.Error, str); log.Write(mgt.LastError); } return(false); } try { bool hasChannel = false; foreach (IChannel chn in ChannelServices.RegisteredChannels) { if (chn is HttpChannel) { hasChannel = true; break; } } if (!hasChannel) { HttpChannel chn = new HttpChannel(); ChannelServices.RegisterChannel(chn, false); } IManagementService helper = Activator.GetObject(typeof(IManagementService), mgt.Config.RemotingUrl) as IManagementService; if (helper == null) { str = "Create remote object failed: " + mgt.Config.RemotingUrl; if (log != null) { log.Write(LogType.Error, str); } return(false); } return(helper.SetServiceStatusAndStartStyle(serviceName, status)); } catch (Exception err) { if (log != null) { str = "Call remting service failed: " + mgt.Config.RemotingUrl; log.Write(LogType.Error, str); log.Write(err); } return(false); } }
/// <summary> /// Creates a new instance of the ZyanConnection class. /// </summary> /// <param name="serverUrl">URL of remote server (e.G. "tcp://server1:46123/myapp").</param> /// <param name="protocolSetup">Protocol and communication settings.</param> /// <param name="credentials">Login credentials.</param> /// <param name="autoLoginOnExpiredSession">Specifies whether the proxy should relogin automatically when the session expired.</param> /// <param name="keepSessionAlive">Specifies whether the session should be automaticly kept alive.</param> public ZyanConnection(string serverUrl, IClientProtocolSetup protocolSetup, Hashtable credentials, bool autoLoginOnExpiredSession, bool keepSessionAlive) { if (string.IsNullOrEmpty(serverUrl)) { throw new ArgumentException(LanguageResource.ArgumentException_ServerUrlMissing, "serverUrl"); } if (protocolSetup == null) { // try to select the protocol automatically protocolSetup = ClientProtocolSetup.GetClientProtocol(serverUrl); if (protocolSetup == null) { throw new ArgumentNullException("protocolSetup"); } } if (!protocolSetup.IsUrlValid(serverUrl)) { throw new ArgumentException(LanguageResource.ArgumentException_ServerUrlIsInvalid, "serverUrl"); } _proxies = new List <WeakReference>(); _protocolSetup = protocolSetup; _sessionID = Guid.NewGuid(); _serverUrl = serverUrl; _autoLoginOnExpiredSession = autoLoginOnExpiredSession; _keepSessionAlive = keepSessionAlive; if (_autoLoginOnExpiredSession) { _autoLoginCredentials = credentials; } _serializationHandling = new SerializationHandlerRepository(); CallInterceptionEnabled = false; _callInterceptors = new CallInterceptorCollection(); RegisterStandardSerializationHandlers(); string[] addressParts = _serverUrl.Split('/'); _componentHostName = addressParts[addressParts.Length - 1]; _remotingChannel = _protocolSetup.CreateChannel(); if (!ZyanSettings.DisableUrlRandomization) { _remotingChannel = ChannelWrapper.WrapChannel(_remotingChannel, _protocolSetup.ChannelName); } if (_remotingChannel != null) { var registeredChannel = ChannelServices.GetChannel(_remotingChannel.ChannelName); if (registeredChannel == null) { ChannelServices.RegisterChannel(_remotingChannel, false); } else { _remotingChannel = registeredChannel; } } else { throw new ApplicationException(LanguageResource.ApplicationException_NoChannelCreated); } var connectionNotification = _remotingChannel as IConnectionNotification; if (connectionNotification != null) { connectionNotification.ConnectionEstablished += Channel_ConnectionEstablished; } string channelName = _remotingChannel.ChannelName; if (credentials != null && credentials.Count == 0) { credentials = null; } try { RemoteDispatcher.Logon(_sessionID, credentials); _registeredComponents = new List <ComponentInfo>(RemoteDispatcher.GetRegisteredComponents()); _sessionAgeLimit = RemoteDispatcher.SessionAgeLimit; } catch (Exception ex) { // unregister remoting channel var registeredChannel = ChannelServices.GetChannel(channelName); if (registeredChannel != null) { ChannelServices.UnregisterChannel(registeredChannel); } // dispose channel if it's disposable var disposableChannel = registeredChannel as IDisposable; if (disposableChannel != null) { disposableChannel.Dispose(); } _remotingChannel = null; _remoteDispatcher = null; throw ex.PreserveStackTrace(); } StartKeepSessionAliveTimer(); lock (_connections) { _connections.Add(this); } }
public static void Main(string[] args) { // Create the server channel. HttpServerChannel serverChannel = new HttpServerChannel(9090); // Register the server channel. ChannelServices.RegisterChannel(serverChannel); //<snippet21> // Display the channel's scheme. Console.WriteLine("The channel scheme is {0}.", serverChannel.ChannelScheme); //</snippet21> //<snippet22> // Display the channel's URI. Console.WriteLine("The channel URI is {0}.", serverChannel.GetChannelUri()); //</snippet22> // Expose an object for remote calls. RemotingConfiguration.RegisterWellKnownServiceType( typeof(RemoteObject), "RemoteObject.rem", WellKnownObjectMode.Singleton); //<snippet23> // Get the channel's sink chain. IServerChannelSink sinkChain = serverChannel.ChannelSinkChain; Console.WriteLine( "The type of the server channel's sink chain is {0}.", sinkChain.GetType().ToString()); //</snippet23> //<snippet24> // See if the channel wants to listen. bool wantsToListen = serverChannel.WantsToListen; Console.WriteLine( "The value of WantsToListen is {0}.", wantsToListen); //</snippet24> //<snippet25> // Parse the channel's URI. string[] urls = serverChannel.GetUrlsForUri("RemoteObject.rem"); if (urls.Length > 0) { string objectUrl = urls[0]; string objectUri; string channelUri = serverChannel.Parse(objectUrl, out objectUri); Console.WriteLine("The object URI is {0}.", objectUri); Console.WriteLine("The channel URI is {0}.", channelUri); Console.WriteLine("The object URL is {0}.", objectUrl); } //</snippet25> // Wait for the user prompt. Console.WriteLine("Press ENTER to exit the server."); Console.ReadLine(); Console.WriteLine("The server is exiting."); }
static void Main(string[] args) { // Read args ParseArgs(args); // Start up the GUI thread InitGUIThread(); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Green, "Starting up SwarmAgent ..."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent with remoting service"); // Register the local agent singleton RemotingConfiguration.RegisterWellKnownServiceType(typeof(Agent), "SwarmAgent", WellKnownObjectMode.Singleton); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent network channels"); // We're going to have two channels for the Agent: one for the actual Agent // application (IPC with infinite timeout) and one for all other remoting // traffic (TCP with infinite timeout that we monitor for drops) IpcChannel AgentIPCChannel = null; TcpChannel AgentTCPChannel = null; while ((Ticking == true) && ((AgentIPCChannel == null) || (AgentTCPChannel == null))) { try { if (AgentIPCChannel == null) { // Register the IPC connection to the local agent string IPCChannelPortName = String.Format("127.0.0.1:{0}", Properties.Settings.Default.AgentRemotingPort); AgentIPCChannel = new IpcChannel(IPCChannelPortName); ChannelServices.RegisterChannel(AgentIPCChannel, false); } if (AgentTCPChannel == null) { // Register the TCP connection to the local agent AgentTCPChannel = new TcpChannel(Properties.Settings.Default.AgentRemotingPort); ChannelServices.RegisterChannel(AgentTCPChannel, false); } } catch (Exception) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Channel already registered, suggesting another SwarmAgent or client is running."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] If you feel this is in error, check your running process list for additional copies of"); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] SwarmAgent or UnrealLightmass (or other client) and consider killing them."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Sleeping for a few seconds and trying again..."); Thread.Sleep(3000); } } // if we're still ticking, we should have both of our channels initialized if (Ticking) { Debug.Assert(AgentIPCChannel != null); Debug.Assert(AgentTCPChannel != null); } else { // Otherwise, we can simply return to exit return; } // Get the agent interface object using the IPC channel string LocalAgentURL = String.Format("ipc://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString()); LocalAgent = ( Agent )Activator.GetObject(typeof(Agent), LocalAgentURL); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Green, " ... initializing SwarmAgent"); // Init the local agent object (if this is the first call to it, it will be created now) bool AgentInitializedSuccessfully = false; try { AgentInitializedSuccessfully = LocalAgent.Init(Process.GetCurrentProcess().Id); } catch (Exception Ex) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with an IPC channel! Falling back to TCP..."); AgentApplication.Log(EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex.ToString()); // Try again with the TCP channel, which is slower but should work LocalAgentURL = String.Format("tcp://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString()); LocalAgent = ( Agent )Activator.GetObject(typeof(Agent), LocalAgentURL); try { AgentInitializedSuccessfully = LocalAgent.Init(Process.GetCurrentProcess().Id); if (AgentInitializedSuccessfully) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] RECOVERED by using TCP channel!"); } } catch (Exception Ex2) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with a TCP channel! Fatal error."); AgentApplication.Log(EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex2.ToString()); ChannelServices.UnregisterChannel(AgentTCPChannel); ChannelServices.UnregisterChannel(AgentIPCChannel); return; } } // Only continue if we have a fully initialized agent if ((LocalAgent != null) && AgentInitializedSuccessfully) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Green, " ... initialization successful, SwarmAgent now running"); // Loop until a quit/restart event has been requested while (!LocalAgent.ShuttingDown()) { try { // If we've stopped ticking, notify the agent that we want to shutdown if (!Ticking) { LocalAgent.RequestShutdown(); } // Maintain the agent itself LocalAgent.MaintainAgent(); // Maintain any running active connections LocalAgent.MaintainConnections(); // Maintain the Agent's cache if (CacheRelocationRequested) { LocalAgent.RequestCacheRelocation(); CacheRelocationRequested = false; } if (CacheClearRequested) { LocalAgent.RequestCacheClear(); CacheClearRequested = false; } if (CacheValidateRequested) { LocalAgent.RequestCacheValidate(); CacheValidateRequested = false; } LocalAgent.MaintainCache(); // Maintain any running jobs LocalAgent.MaintainJobs(); // If this is a deployed application which is configured to auto-update, // we'll check for any updates and, if there are any, request a restart // which will install them prior to restarting #if !__MonoCS__ if ((AgentApplication.DeveloperOptions.UpdateAutomatically) && (ApplicationDeployment.IsNetworkDeployed) && (DateTime.UtcNow > NextUpdateCheckTime)) { if (CheckForUpdates()) { LocalAgent.RequestRestart(); } NextUpdateCheckTime = DateTime.UtcNow + TimeSpan.FromMinutes(1); } #endif } catch (Exception Ex) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.Message); AgentApplication.Log(EVerbosityLevel.ExtraVerbose, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.ToString()); } // Sleep for a little bit Thread.Sleep(500); } // Let the GUI destroy itself RequestQuit(); bool AgentIsRestarting = LocalAgent.Restarting(); // Do any required cleanup LocalAgent.Destroy(); ChannelServices.UnregisterChannel(AgentTCPChannel); ChannelServices.UnregisterChannel(AgentIPCChannel); // Now that everything is shut down, restart if requested if (AgentIsRestarting) { ClearCache(); InstallAllUpdates(); Application.Restart(); } } }
/// <summary> /// Creates a globally reachable, managed IPC-Port. /// </summary> /// <remarks> /// Because it is something tricky to get a port working for any constellation of /// target processes, I decided to write a proper wrapper method. Just keep the returned /// <see cref="IpcChannel"/> alive, by adding it to a global list or static variable, /// as long as you want to have the IPC port open. /// </remarks> /// <typeparam name="TRemoteObject"> /// A class derived from <see cref="MarshalByRefObject"/> which provides the /// method implementations this server should expose. /// </typeparam> /// <param name="InObjectMode"> /// <see cref="WellKnownObjectMode.SingleCall"/> if you want to handle each call in an new /// object instance, <see cref="WellKnownObjectMode.Singleton"/> otherwise. The latter will implicitly /// allow you to use "static" remote variables. /// </param> /// <param name="RefChannelName"> /// Either <c>null</c> to let the method generate a random channel name to be passed to /// <see cref="IpcConnectClient"/> or a predefined one. If you pass a value unequal to /// <c>null</c>, you shall also specify all SIDs that are allowed to connect to your channel! /// </param> /// <param name="InAllowedClientSIDs"> /// If no SID is specified, all authenticated users will be allowed to access the server /// channel by default. You must specify an SID if <paramref name="RefChannelName"/> is unequal to <c>null</c>. /// </param> /// <returns> /// An <see cref="IpcChannel"/> that shall be keept alive until the server is not needed anymore. /// </returns> /// <exception cref="System.Security.HostProtectionException"> /// If a predefined channel name is being used, you are required to specify a list of well known SIDs /// which are allowed to access the newly created server. /// </exception> /// <exception cref="RemotingException"> /// The given channel name is already in use. /// </exception> public static IpcServerChannel IpcCreateServer <TRemoteObject>( ref String RefChannelName, WellKnownObjectMode InObjectMode, params WellKnownSidType[] InAllowedClientSIDs) where TRemoteObject : MarshalByRefObject { String ChannelName = RefChannelName; if (ChannelName == null) { ChannelName = GenerateName(); } /////////////////////////////////////////////////////////////////// // create security descriptor for IpcChannel... System.Collections.IDictionary Properties = new System.Collections.Hashtable(); Properties["name"] = ChannelName; Properties["portName"] = ChannelName; DiscretionaryAcl DACL = new DiscretionaryAcl(false, false, 1); if (InAllowedClientSIDs.Length == 0) { if (RefChannelName != null) { throw new System.Security.HostProtectionException("If no random channel name is being used, you shall specify all allowed SIDs."); } // allow access from all users... Channel is protected by random path name! DACL.AddAccess( AccessControlType.Allow, new SecurityIdentifier( WellKnownSidType.WorldSid, null), -1, InheritanceFlags.None, PropagationFlags.None); } else { for (int i = 0; i < InAllowedClientSIDs.Length; i++) { DACL.AddAccess( AccessControlType.Allow, new SecurityIdentifier( InAllowedClientSIDs[i], null), -1, InheritanceFlags.None, PropagationFlags.None); } } CommonSecurityDescriptor SecDescr = new CommonSecurityDescriptor(false, false, ControlFlags.GroupDefaulted | ControlFlags.OwnerDefaulted | ControlFlags.DiscretionaryAclPresent, null, null, null, DACL); ////////////////////////////////////////////////////////// // create IpcChannel... BinaryServerFormatterSinkProvider BinaryProv = new BinaryServerFormatterSinkProvider(); BinaryProv.TypeFilterLevel = TypeFilterLevel.Full; IpcServerChannel Result = new IpcServerChannel(Properties, BinaryProv, SecDescr); ChannelServices.RegisterChannel(Result, false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(TRemoteObject), ChannelName, InObjectMode); RefChannelName = ChannelName; return(Result); }
public static void Init(string[] args) { Engine.Engine.Init(); Engine.Engine.InitSessionManager(); string channel = (string)Engine.Engine.Config["Server/Channel"]; string formatter = (string)Engine.Engine.Config["Server/Formatter"]; string host = (string)Engine.Engine.Config["Server/Host"]; string bindAddress = (string)Engine.Engine.Config["Server/BindAddress"]; int port = (int)Engine.Engine.Config["Server/Port"]; IDictionary props = new Hashtable(); props["port"] = port.ToString(); if (host != null) { props["machineName"] = host; } if (bindAddress != null) { props["bindTo"] = bindAddress; } switch (channel) { case "TCP": props["name"] = "TcpChannel"; BinaryClientFormatterSinkProvider cprovider = new BinaryClientFormatterSinkProvider(); BinaryServerFormatterSinkProvider sprovider = new BinaryServerFormatterSinkProvider(); // required for MS .NET 1.1 sprovider.TypeFilterLevel = TypeFilterLevel.Full; #if LOG4NET _Logger.Debug("Registering TcpChannel port: " + props["port"]); #endif try { ChannelServices.RegisterChannel(new TcpChannel(props, cprovider, sprovider), false); } catch (System.Net.Sockets.SocketException ex) { Console.WriteLine("Could not register remoting channel on port {0} " + "(server already running on that port?) Error: " + ex.Message, port); Environment.Exit(1); } break; #if CHANNEL_TCPEX case "TcpEx": props["name"] = "TcpExChannel"; #if LOG4NET _Logger.Debug("Registering TcpExChannel port: " + props["port"]); #endif ChannelServices.RegisterChannel(new TcpExChannel(props, null, null), false); break; #endif case "HTTP": props["name"] = "HttpChannel"; #if LOG4NET _Logger.Debug("Registering HttpChannel port: " + props["port"]); #endif ChannelServices.RegisterChannel(new HttpChannel(props, null, null), false); break; default: Console.WriteLine("Unknown channel (" + channel + "), aborting..."); Environment.Exit(1); break; } // register the SessionManager for .NET remoting RemotingServices.Marshal(Engine.Engine.SessionManager, "SessionManager"); #if LOG4NET _Logger.Info("Spawned remoting server with channel: " + channel + " formatter: " + formatter + " port: " + port); #endif if ((Environment.OSVersion.Platform == PlatformID.Unix) || (Environment.OSVersion.Platform == PlatformID.MacOSX)) { // Register shutdown handlers #if LOG4NET _Logger.Info("Registering signal handlers"); #endif UnixSignal[] shutdown_signals = { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM), }; Thread signal_thread = new Thread(() => { var index = UnixSignal.WaitAny(shutdown_signals); #if LOG4NET _Logger.Info("Caught signal " + shutdown_signals[index].Signum.ToString() + ", shutting down"); #endif Engine.Engine.Shutdown(); }); signal_thread.Start(); } Thread.CurrentThread.Join(); #if LOG4NET _Logger.Info("Shutting down remoting server..."); #endif }
private static void RunAsController(string[] arguments) { if (arguments == null || arguments.Length < 2) { Console.WriteLine("Invalid arguments!"); } else { IConfigurationSource configurationSource = ConfigurationManager.GetSection("superSocket") as IConfigurationSource; if (configurationSource == null) { Console.WriteLine("SuperSocket configiration is required!"); } else { ChannelServices.RegisterChannel((IChannel) new IpcClientChannel(), false); IBootstrap bootstrap = (IBootstrap)null; try { bootstrap = (IBootstrap)Activator.GetObject(typeof(IBootstrap), string.Format("ipc://SuperSocket.Bootstrap[{0}]/Bootstrap.rem", (object)Math.Abs(AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[1] { Path.DirectorySeparatorChar }).GetHashCode()))); } catch (RemotingException) { if (configurationSource.Isolation != IsolationMode.Process) { Console.WriteLine("Error: the SuperSocket engine has not been started!"); return; } } Program.RegisterCommands(); string key = arguments[1]; ControlCommand controlCommand; if (!Program.m_CommandHandlers.TryGetValue(key, out controlCommand)) { Console.WriteLine("Unknown command"); } else { try { if (controlCommand.Handler(bootstrap, Enumerable.ToArray <string>(Enumerable.Skip <string>((IEnumerable <string>)arguments, 1)))) { Console.WriteLine("Ok"); } } catch (Exception ex) { Console.WriteLine("Failed. " + ex.Message); } } } } }
/// <summary> /// Implements remote server. /// </summary> private static void RunServer(string serverPort, string semaphoreName, int clientProcessId) { if (!AttachToClientProcess(clientProcessId)) { return; } // Disables Windows Error Reporting for the process, so that the process fails fast. // Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) // Note that GetErrorMode is not available on XP at all. if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0)) { SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); } IpcServerChannel serverChannel = null; IpcClientChannel clientChannel = null; try { using (var semaphore = Semaphore.OpenExisting(semaphoreName)) { // DEBUG: semaphore.WaitOne(); var serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; var clientProvider = new BinaryClientFormatterSinkProvider(); clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider); ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false); serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider); ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Service), ServiceName, WellKnownObjectMode.Singleton); using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { var c = new Control(); c.CreateControl(); s_UIThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } // the client can instantiate interactive host now: semaphore.Release(); } s_clientExited.Wait(); } finally { if (serverChannel != null) { ChannelServices.UnregisterChannel(serverChannel); } if (clientChannel != null) { ChannelServices.UnregisterChannel(clientChannel); } } // force exit even if there are foreground threads running: Environment.Exit(0); }
//args - server_id, url, max_faults, min_delay, max_delay static void Main(string[] args) { string server_id = args[0]; string url = args[1]; string max_faults = args[2]; string min_delay = args[3]; string max_delay = args[4]; //tcp://localhost:8080/Client --> example string port = url.Split(':')[2].Split('/')[0]; //8080 string service = url.Split(':')[2].Split('/')[1]; //Client //create tcp channel var provider = new BinaryServerFormatterSinkProvider(); provider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; IDictionary props = new Hashtable(); props["port"] = Int32.Parse(port); TcpChannel channel = new TcpChannel(props, null, provider); //TcpChannel channel = new TcpChannel(Int32.Parse(port)); ChannelServices.RegisterChannel(channel, false); int max_faults_int = Int32.Parse(max_faults); int min_delay_int = Int32.Parse(min_delay); int max_delay_int = Int32.Parse(max_delay); //Initialize debugger Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .WriteTo.File("../logs/" + server_id + "_.log", rollingInterval: RollingInterval.Minute, rollOnFileSizeLimit: true) .CreateLogger(); // Log.Information(""); // Log.Debug(""); // Log.Error(""); Log.Debug("creating objects"); //create server, puppeteer and serverToServer Server server = new Server(server_id, url, max_faults_int, min_delay_int, max_delay_int); ServerPuppeteer puppeteer = new ServerPuppeteer(server); ServerToServer serverToServer = new ServerToServer(server); Log.Debug("marshalling objects"); //marshall objects RemotingServices.Marshal( puppeteer, service + ServerInfo.puppeteerExtension, typeof(ServerPuppeteer)); RemotingServices.Marshal( serverToServer, service + ServerInfo.toServerExtension, typeof(ServerToServer)); RemotingServices.Marshal( server, service, typeof(Server)); //DEBUG Log.Debug("New server {server} created", server_id); //prevent process from closing System.Console.ReadLine(); }
/// <summary> /// Remotes this instance across a channel /// - if the own end point is valid: /// - register a new channel, if not already done. /// - if successful, then marshal this GNode object over the remoting channel /// </summary> private void RemoteSelf() { if (_OwnEP != null) { switch (_OwnEP.RemotingMechanism) { case (RemotingMechanism.TcpBinary): { #region .NET Remoting Publish if (!_ChannelRegistered) { try { _Channel = new TcpChannel(_OwnEP.Port); //Hashtable properties = new Hashtable(); //// the name must be Empty in order to allow multiple TCP channels //properties.Add("name", String.Empty); //properties.Add("port", _OwnEP.Port); //_Channel = new TcpChannel( // properties, // new BinaryClientFormatterSinkProvider(), // new BinaryServerFormatterSinkProvider()); ChannelServices.RegisterChannel(_Channel, false); _ChannelRegistered = true; } catch (Exception e) { if ( object.ReferenceEquals(e.GetType(), typeof(System.Runtime.Remoting.RemotingException)) /* assuming: "The channel tcp is already registered." */ | object.ReferenceEquals(e.GetType(), typeof(SocketException)) /* assuming: "Only one usage of each socket address (protocol/network address/port) is normally permitted" */ ) { _ChannelRegistered = true; } else { UnRemoteSelf(); throw new RemotingException("Could not register channel while trying to remote self: " + e.Message, e); } } } if (_ChannelRegistered) { try { logger.Info("Trying to publish a GNode at : " + _RemoteObjPrefix); RemotingServices.Marshal(this, _RemoteObjPrefix); logger.Info("GetObjectURI from remoting services : " + RemotingServices.GetObjectUri(this)); logger.Info("Server object type: " + RemotingServices.GetServerTypeForUri(RemotingServices.GetObjectUri(this)).FullName); } catch (Exception e) { UnRemoteSelf(); throw new RemotingException("Could not remote self.", e); } } break; #endregion } case RemotingMechanism.WCFCustom: { #region Custom WCF Publish try { _ServiceHost = new ServiceHost(this, new Uri(_OwnEP.FullAddress)); _ServiceHost.Open(); } catch (Exception e) { UnRemoteSelf(); throw e; //throw new Exception("Could not remote self.", e); } break; #endregion } case RemotingMechanism.WCFTcp: { #region Tcp WCF Publish try { //create a new binding _OwnEP.Binding = WCFBinding.NetTcpBinding; System.ServiceModel.NetTcpBinding tcpBin = (System.ServiceModel.NetTcpBinding)Utility.WCFUtils.GetWCFBinding(_OwnEP); Type contractType = null; if (this is Alchemi.Core.IExecutor) { contractType = typeof(Alchemi.Core.IExecutor); } else if (this is Alchemi.Core.IManager) { contractType = typeof(Alchemi.Core.IManager); } else if (this is Alchemi.Core.IOwner) { contractType = typeof(Alchemi.Core.IOwner); } _ServiceHost = new ServiceHost(this, new Uri(_OwnEP.FullPublishingAddress)); Utility.WCFUtils.SetPublishingServiceHost(_ServiceHost); _ServiceHost.AddServiceEndpoint(contractType, tcpBin, _OwnEP.FullPublishingAddress); _ServiceHost.Open(); } catch (Exception e) { UnRemoteSelf(); throw e; //throw new Exception("Could not remote self.", e); } break; #endregion } case RemotingMechanism.WCFHttp: { #region Http WCF Publish try { //create a new binding _OwnEP.Binding = WCFBinding.WSHttpBinding; System.ServiceModel.WSHttpBinding wsHttpBin = (System.ServiceModel.WSHttpBinding)Utility.WCFUtils.GetWCFBinding(_OwnEP); Type contractType = null; if (this is Alchemi.Core.IExecutor) { contractType = typeof(Alchemi.Core.IExecutor); } else if (this is Alchemi.Core.IManager) { contractType = typeof(Alchemi.Core.IManager); } else if (this is Alchemi.Core.IOwner) { contractType = typeof(Alchemi.Core.IOwner); } _ServiceHost = new ServiceHost(this, new Uri(_OwnEP.FullPublishingAddress)); Utility.WCFUtils.SetPublishingServiceHost(_ServiceHost); _ServiceHost.AddServiceEndpoint(contractType, wsHttpBin, _OwnEP.FullPublishingAddress); _ServiceHost.Open(); } catch (Exception e) { UnRemoteSelf(); throw e; //throw new Exception("Could not remote self.", e); } break; #endregion } case RemotingMechanism.WCF: { #region WCF Publish try { //create a new binding System.ServiceModel.Channels.Binding binding = Utility.WCFUtils.GetWCFBinding(_OwnEP); Type contractType = null; if (this is Alchemi.Core.IExecutor) { contractType = typeof(Alchemi.Core.IExecutor); } else if (this is Alchemi.Core.IManager) { contractType = typeof(Alchemi.Core.IManager); } else if (this is Alchemi.Core.IOwner) { contractType = typeof(Alchemi.Core.IOwner); } _ServiceHost = new ServiceHost(this, new Uri(_OwnEP.FullPublishingAddress)); Utility.WCFUtils.SetPublishingServiceHost(_ServiceHost); _ServiceHost.AddServiceEndpoint(contractType, binding, _OwnEP.FullPublishingAddress); _ServiceHost.Open(); } catch (Exception e) { UnRemoteSelf(); throw e; //throw new Exception("Could not remote self.", e); } break; #endregion } } } }
static int Main(string[] args) { Console.WriteLine($"Famicom Dumper Client v{Assembly.GetExecutingAssembly().GetName().Version.Major}.{Assembly.GetExecutingAssembly().GetName().Version.Minor}"); Console.WriteLine($" Commit {Properties.Resources.gitCommit} @ https://github.com/ClusterM/famicom-dumper-client"); Console.WriteLine(" (c) Alexey 'Cluster' Avdyukhin / https://clusterrr.com / [email protected]"); Console.WriteLine(); startTime = DateTime.Now; string port = "auto"; string mapper = "0"; string psize = null; string csize = null; string filename = null; bool battery = false; string csFile = null; string[] csArgs = new string[0]; string unifName = null; string unifAuthor = null; bool reset = false; bool silent = true; bool needCheck = false; bool writePBBs = false; List <int> badSectors = new List <int>(); int testCount = -1; uint tcpPort = 26672; bool ignoreBadSectors = false; string remoteHost = null; byte fdsSides = 1; bool fdsUseHeader = true; bool fdsDumpHiddenFiles = false; try { if (args.Length == 0 || args.Contains("help") || args.Contains("--help")) { PrintHelp(); return(0); } string command = args[0].ToLower(); for (int i = 1; i < args.Length; i++) { string param = args[i]; if (param == "-") { csArgs = args.Skip(i + 1).ToArray(); break; } while (param.StartsWith("-") || param.StartsWith("—")) { param = param.Substring(1); } string value = i < args.Length - 1 ? args[i + 1] : ""; switch (param.ToLower()) { case "p": case "port": port = value; i++; break; case "m": case "mapper": mapper = value; i++; break; case "f": case "file": filename = value; i++; break; case "fds-sides": fdsSides = byte.Parse(value); i++; break; case "fds-no-header": fdsUseHeader = false; break; case "fds-dump-hidden": fdsDumpHiddenFiles = true; break; case "csfile": case "cs-file": case "scriptfile": case "script-file": csFile = value; i++; break; case "psize": case "prg-size": psize = value; i++; break; case "csize": case "chr-size": csize = value; i++; break; case "battery": battery = true; break; case "unifname": case "unif-name": unifName = value; i++; break; case "unifauthor": case "unif-author": unifAuthor = value; i++; break; case "reset": reset = true; break; case "sound": silent = false; break; case "check": case "verify": needCheck = true; break; case "lock": writePBBs = true; break; case "testcount": case "test-count": testCount = int.Parse(value); i++; break; case "badsectors": case "bad-sectors": foreach (var v in value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { badSectors.Add(int.Parse(v)); } i++; break; case "tcpport": case "tcp-port": tcpPort = uint.Parse(value); i++; break; case "host": remoteHost = value; i++; break; case "ignorebadsectors": case "ignore-bad-sectors": ignoreBadSectors = true; break; default: Console.WriteLine("Unknown option: " + param); PrintHelp(); return(2); } } if (command == "list-mappers") { ListMappers(); return(0); } FamicomDumperConnection dumper; if (string.IsNullOrEmpty(remoteHost)) { dumper = new FamicomDumperConnection(port); dumper.Open(); } else { BinaryServerFormatterSinkProvider binaryServerFormatterSinkProvider = new BinaryServerFormatterSinkProvider(); BinaryClientFormatterSinkProvider binaryClientFormatterSinkProvider = new BinaryClientFormatterSinkProvider(); binaryServerFormatterSinkProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; var dict = new System.Collections.Hashtable(); dict["name"] = "FamicomDumperClient"; dict["secure"] = false; var channel = new TcpChannel(dict, binaryClientFormatterSinkProvider, binaryServerFormatterSinkProvider); ChannelServices.RegisterChannel(channel, false); dumper = (FamicomDumperConnection)Activator.GetObject(typeof(IFamicomDumperConnection), $"tcp://{remoteHost}:{tcpPort}/dumper"); var lifetime = dumper.GetLifetimeService(); } try { Console.Write("Dumper initialization... "); bool prgInit = dumper.DumperInit(); if (!prgInit) { throw new IOException("Can't init dumper"); } Console.WriteLine("OK"); if (reset) { Reset(dumper); } if (!string.IsNullOrEmpty(csFile)) { CompileAndExecute(csFile, dumper, csArgs); } switch (command) { case "reset": if (!reset) { Reset(dumper); } break; case "list-mappers": ListMappers(); break; case "dump": Dump(dumper, filename ?? "output.nes", mapper, ParseSize(psize), ParseSize(csize), unifName, unifAuthor, battery); break; case "dump-fds": FDS.DumpFDS(dumper, filename ?? "output.fds", fdsSides, fdsDumpHiddenFiles, fdsUseHeader); break; case "read-prg-ram": case "dump-prg-ram": case "dump-sram": ReadPrgRam(dumper, filename ?? "savegame.sav", mapper); break; case "write-fds": if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("Please specify ROM filename using --file argument"); } FDS.WriteFDS(dumper, filename, needCheck); break; case "write-prg-ram": case "write-sram": if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("Please specify ROM filename using --file argument"); } WritePrgRam(dumper, filename, mapper); break; case "test-prg-ram": case "test-sram": TestPrgRam(dumper, mapper); break; case "test-prg-coolgirl": case "test-prg-ram-coolgirl": case "test-sram-coolgirl": CoolgirlWriter.TestPrgRam(dumper); break; case "test-battery": TestBattery(dumper, mapper); break; case "test-chr-ram": TestChrRam(dumper); break; case "test-chr-coolgirl": case "test-chr-ram-coolgirl": CoolgirlWriter.TestChrRam(dumper, chrSize: ParseSize(csize)); break; case "test-coolgirl": CoolgirlWriter.FullTest(dumper, testCount, chrSize: ParseSize(csize)); break; case "test-bads-coolgirl": CoolgirlWriter.FindBads(dumper, silent); break; case "read-crc-coolgirl": CoolgirlWriter.ReadCrc(dumper); break; case "dump-tiles": DumpTiles(dumper, filename ?? "output.png", mapper, ParseSize(csize)); break; case "write-coolboy": case "write-coolboy-direct": case "write-coolboy-gpio": // for backward compatibility if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("Please specify ROM filename using --file argument"); } CoolboyWriter.Write(dumper, filename, badSectors, silent, needCheck, writePBBs, ignoreBadSectors); break; case "write-coolgirl": if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("Please specify ROM filename using --file argument"); } CoolgirlWriter.Write(dumper, filename, badSectors, silent, needCheck, writePBBs, ignoreBadSectors); break; case "write-eeprom": if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("Please specify ROM filename using --file argument"); } WriteEeprom(dumper, filename); break; case "info-coolboy": CoolboyWriter.PrintFlashInfo(dumper); break; case "info-coolgirl": CoolgirlWriter.PringFlashInfo(dumper); break; case "bootloader": Bootloader(dumper); break; case "script": if (string.IsNullOrEmpty(csFile)) { throw new ArgumentNullException("Please specify C# script using --cs-file argument"); } break; case "server": StartServer(dumper, tcpPort); break; default: Console.WriteLine("Unknown command: " + command); PrintHelp(); return(2); } #if DEBUG var timePassed = DateTime.Now - startTime; if (timePassed.TotalMinutes >= 60) { Console.WriteLine($"Done in {timePassed.Hours}:{timePassed.Minutes:D2}:{timePassed.Seconds:D2}"); } else if (timePassed.TotalSeconds >= 10) { Console.WriteLine($"Done in {timePassed.Minutes:D2}:{timePassed.Seconds:D2}"); } else { Console.WriteLine($"Done in {(int)timePassed.TotalMilliseconds}ms"); } #endif if (!silent) { PlayDoneSound(); } } finally { if (string.IsNullOrEmpty(remoteHost)) { dumper.Dispose(); } } } catch (Exception ex) { Console.WriteLine($"ERROR {ex.GetType()}: " + ex.Message #if DEBUG + ex.StackTrace #endif ); if (!silent) { PlayErrorSound(); } return(1); } return(0); }
private imagetool() { ChannelServices.RegisterChannel(new TcpClientChannel("shibie", new BinaryClientFormatterSinkProvider()), false); UjYdAtsjXq = (Get51Code)Activator.GetObject(typeof(Get51Code), "tcp://localhost:80/Get51Code"); }
public void StartServer() { ChannelServices.RegisterChannel(ipcChannel, false); }