I am trying to make a simple server thread in QT to accept a connection, however although the server is listening (I can connect with my test app) I can't get the newConnection() signal to be acted on.
Any help as to what I'm missing here would be much appreciated!
class CServerThread : public QThread
{
Q_OBJECT
protected:
void run();
private:
QTcpServer* server;
public slots:
void AcceptConnection();
};
void CServerThread::run()
{
server = new QTcpServer;
QObject::connect(server, SIGNAL(newConnection()), this, SLOT(AcceptConnection()));
server->listen(QHostAddress::Any, 1000); // Any port in a storm
exec(); // Start event loop
}
void CServerThread::AcceptConnection()
{
OutputDebugStringA("\n***** INCOMING CONNECTION"); // This is never called!
}
First of all I can say that your server lives in new thread while CServerThread instance lives in another thread (in the thread this instance was created). Signal/slot connection you are creating is inderect and uses thread save event delivery between events loops of two different threads. It actually can cause such problem if thread where you creating CServerThread doesn't have Qt event loop running.
I suggest you to create some MyServer class which creates QTcpServer and calls listen and connects QTcpServer::newConnection() signal to its own slot. Then rewrite your server thread run method to something like this:
void CServerThread::run() {
server = new MyServer(host,port);
exec(); // Start event loop
}
In this approach both QTcpServer and newConnection processing object lives in the same thread. Such situation is easier to handle.
I have one really simple working example:
Header: http://qremotesignal.googlecode.com/svn/tags/1.0.0/doc/html/hello_2server_2server_8h-example.html
Source: http://qremotesignal.googlecode.com/svn/tags/1.0.0/doc/html/hello_2server_2server_8cpp-example.html
Related
In start, it works fine, but after a certain time (1-2 hours) it crashes with the following exception in server logs.
ERROR 1 --- [-ignite-server%] : JVM will be halted immediately due to the failure: [failureCtx=FailureContext [type=CRITICAL_ERROR, err=class o.a.i.i.IgniteDeploymentCheckedException: Failed to obtain deployment for class: com.event.audit.AuditEventListener$$Lambda$1484/0x0000000800a7ec40]]
public static void remoteListener(Ignite ignite) {
// This optional local callback is called for each event notification
// that passed remote predicate listener.
IgniteBiPredicate<UUID, CacheEvent> locLsnr = new IgniteBiPredicate<UUID, CacheEvent>() {
#Override public boolean apply(UUID nodeId, CacheEvent evt) {
System.out.println("Listener caught an event");
//--- My custom code to persists the event in another cache
};
IgnitePredicate<CacheEvent> remoteListener = cacheEvent -> {
return true;
};
// Register event listeners on all nodes to listen for task events.
UUID lsnrId = ignite.events(ignite.cluster()).remoteListen(locLsnr, remoteListener, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);
}
}
As I understand you, you try to perform cache operations in event listener:
//--- My custom code to persists the event in another cache
Event listeners are called under the locks and this is bad idea to make any other cache operations in listeners. I suppose it could be the root cause of your issue.
Try to change you design, for example you can add your caught event in a queue and then read this queue in another thread and save the data in another cache.
We have our application hosted on Azure Cloud Service containing a Web Role and a Worker Role. The worker role is used for running workflows using Windows Workflow Foundation and other processing works.
We are facing an issue where on encountering a Task.Delay, the thread stops responding in the Worker Role. Initially we were using the Task.Delay in a Custom Code Activity inside Workflow Foundation and on encountering the Task.Delay, the subsequent activities in the workflow would never get triggered. We tried to modify the logic by using a delay activity but faced the same issue.
Recently we changed the logic where are executing a method from the activity (in a fire-and-forget fashion) and calling Task.Delay in that method. But even in this mechanism we are still facing the same problem where the thread stops responding as soon as it hits Task.Delay.
public class CommandStatusCheckerActivity : BaseCodeActivity<Job> //Last Activity in the Workflow
{
protected override Job Execute(CodeActivityContext context)
{
var job = JobContext.Get(context);
var statusUpdater = new JobStatusUpdaterAsync();
//Fire and Forget
Task.Run(
() => statusUpdater.Update(job));
return job;
}
}
public class JobStatusUpdaterAsync
{
public JobStatusUpdaterAsync()
{
//Initialization
}
public void Update(Job job)
{
var iteration = 1;
do
{
_tableLogger.LogMessage(“Sleep Started”);
Task.Delay(backoffDelay).Wait();
_tableLogger.LogMessage(“Active Again”); //This Line is never executed
//Actual Polling Logic
iteration++;
} while (ellapsedTime < timeout && inprogressItems.Any());
}
}
I would like to call out that at the same time there are multiple operations which are happening in the worker role and all those threads are getting completed successfully. But none of the other threads have a Task.Delay in them.
Surprisingly we cannot reproduce the same situation in Local machine, it's happening only in our Cloud Service Worker Role.
Out Worker Role Size in Standard_D2.
Any guidance would be appreciated.
We have a process that is executed as a windows service,
This process serves as an interface server processing incoming messages, transforms them and sends them out to another interface.
it is a rather heavy process, it needs to load a lot of things into memory and that takes some time (few minutes).
due to its nature, when we start it using its windows service, it remains in "starting" status for a very long time (sometimes more than 20 minutes)
even when we can see the process already works and process messages just fine (going by its logs).
so the question is - when is a service considered "starting" and when is it considered "started"? based on what factors?
Starting status finish when onstart is completed.
You should write starting code after onstart event.
puclic class Service1
{
private Timer timer = new Timer();
protected override void OnStart(string[] args)
{
this.timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
this.timer.Interval = 1 * 1000; // 1 second
this.timer.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
this.timer.Enabled = false; // OnElapsedTime run only one time
// Write your code
}
}
I am doing a windows service (call it SampleService), every is fine. When I started then stopped service through Windows Service Management Tool (service.msc), it run properly.
But my service will be request Start and Stop by another application. So I will not use Windows Service Management Tool in this case.
This is my service implement.
using System.ServiceProcess;
public partial class SampleService : ServiceBase
{
public SampleService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteLog("OnStart");
// Doing start service logic down here
// Some service logic like create some files.
// Or just leave it empty like a brand new Windows Service.
}
protected override void OnStop()
{
this.WriteLog("OnStop");
// Doing clean service logic down here.
// Some service logic like: delete files.
// Or just leave it empty like a brand new Windows Service.
}
static readonly object synObject = new object();
public void WriteLog(string message)
{
if (string.IsNullOrEmpty(message))
{
return;
}
// Write log.
lock (synObject)
{
using (var wr = new StreamWriter(#"C:\logfile.txt", true))
{
wr.WriteLine(DateTime.Now + "-" + message);
}
}
}
}
And this is code logic use to Start and Stop service inside my another application. I can not modify this another application. The bellow source code simulate what happen.
class Program
{
static void Main(string[] args)
{
ServiceController sc = new ServiceController("SampleService");
// start service
sc.Start();
// doing some logic cost deltaTime or just stand by in deltaTime.
Thread.Sleep(deltaTime);
try
{
// stop service first time, nothing happen.
sc.Stop();
}
catch
{
}
try
{
// stop service second times, by dump people or apllication.
sc.Stop();
}
catch
{
// It got an exception here: "The service cannot accept control messages at this time".
// But the service did stopped.
}
}
}
The problem is:"When deltaTime is too short (bellow 3000ms with empty OnStart(), OnStop()), Service will stop incorrectly. The output log OnStop will never show up, that mean OnStop method did not called.
My service will doing clean up work in OnStop (like delete some file), but if it not be called, these files still there.
I cannot change logic of another application but I can change SampleService.
I want to ask:
Is this an Windows Service base issue and I cant do anything with it?
What ever it is, can I do clean up some where else?
Thank you!
So, what happened in my project was the following:
I have a singleton which is defined in a usual way:
Singleton* Singleton::getInstance()
{
static Singleton instance;
return &instance;
}
in its constructor, this singleton object initializes a CORBA ORB and started running it in a separate (boost)thread(wrapper) similar to this:
CorbaController::CorbaController()
{
}
CorbaController::~CorbaController()
{
if(!CORBA::is_nil(_orb))
_orb->shutdown(true);
}
void CorbaController::run()
{
_orb->run();
}
bool CorbaController::initCorba(const std::string& ip, unsigned long port)
{
// init CORBA
// ...
// let the ORB execute in a dedicated thread since the run operation is blocking
start();
return true;
}
Now the normal behavior when destructing the CorbaController is that it calls shutdown on the ORB in its destructor, the run method then jumps out of orb.run() and finishes the separate thread. However this only works if the CorbaController is deleted explicitly or defined as a local or class variable which then runs out of scope at some point.
If I rely on the singleton's static variable being cleaned up at the end of the program though, the orb.shutdown() deadlocks because the ACE/TAO lib can't aquire a semaphore on some object to be destructed with the ORB shutdown.
Does anybody have an idea of what might be the problem here? Can this be a threading problem, i.e. that the thread which constructrs the singleton (and also runs the main function of my application) is different from the thread cleaning up static memory instances?
You have to shuytdown and destroy the ORB during the regular shutdown of the application, doing it in the destructor of a static object is really too late. Add a shutdown() method to your CORBA Controller which does a shutdown and destroy of the ORB.