Trying to understand What is IConnectionPoint and how this is connected to IConnectionPointContainer,IEnumConnectionPoints,IEnumConnections and EventHandling.
Read the artcicles from MSDN and CodeProject which is explaining a about other methods like: QueryInterface() and otherthings.
I am unable to figure out how all these things(IConnectionPointContainer,IEnumConnectionPoints,IEnumConnections) are interconnected with eachother and event Handling.
I just want to create a simpleClient which Will trigger an event in COM object.
If there are any articles or code snippet that can explain how things are related to each other with simple and small chunk of code will be helpfull.
Worth mentioning that I have started development in C recently, a beginner.
Edit #sharptooth
For the Line "typically your client will receive events and the COM object will trigger those events. "
From many articles, What I understood is When we use connection points at that point,
the client exposes a set of methods that the server uses.
I am just Outlining portion of the article from TechRepublich:
Client server vs. sink source
So the main difference between normal programming with COM in a standard client-server system and using connection points is that in the standard client-server case, the server exposes a list of methods that the client employs, and in the connection point case, the client exposes a set of methods that the server uses.
Looks like you get the big picture wrong. Typically your client will receive events and the COM object will trigger those events. To achieve this the client requests (QueryInterface()) the IConnectionPointContainer interface, calls IConnectionPointContainer::FindConnectionPoint() and IConnectionPoint::Advise() and passes a pointer to itself or some subobject there.
The client will have to implement some events interface (the one GUID of which is passed into IConnectionPointContainer::FindConnectionPoint()). Once subscribed (advised) the client will receive calls from the COM server - the events.
Typically the COM server does something routinely and decides to notify clients of it (say a user moves the mouse in an ActiveX control) - it just gets an array of pointers to event receivers and calls a method it wants on that interface.
COM events are in fact an implementation of callbacks. The same way you use callback in C++ (or C or any other languages supporting function pointers or interfaces) you use events in COM. Yes, you're right that when the server triggers the event the client in fact acts as a server reacting to the event. That's a callback scenario - the other code calls your functionality. In this case the server calls your implementation of the events interface.
These two articles provide useful information:
https://devblogs.microsoft.com/oldnewthing/?p=4113
https://devblogs.microsoft.com/oldnewthing/20130612-00/?p=4103
What #sharptooth forgot to mention is, the pointer passed to IConnectionPoint::Advise must be a pointer to a COM object.
This means It must not only implement the particular events interface but also the IUnknown interface.
Related
I've currently coded a server/client implementation in C++, where two clients connect to a server. I'm expecting from previous experience (I'm new to C++) that each client (and the server) will have an event handler, and events will come in when either the client wants to send a message to the server, or the client has received a message from the server. You can view it as a chat server; the 'outgoing' event from the client could be the triggered by the user typing something in the console, and the 'incoming' event could be triggered by receiving data from the server.
Is there a standard way of coding this in C++? I'd ideally like to register callback functions for each possible event type, and for the callback function registered to be passed back as a context to the event handler when each event is received, so I can process each event in its specific handling function. And of course once the event has been handled, I want my program to fall back into its event loop.
Any ideas? I'm very comfortable with the event-driven style of programming so would prefer to keep it this way if possible rather than learning entirely new paradigms.
C++ does not have a built-in event handler system (unlike, say, C# and delegates) but there exists plenty of libraries to do that. libsigc++ is one of them.
As a result, any library you use for networking will also have to provide event handling code, either their own or using another library. And if you're rolling out your own networking code, I honestly think creating your own event handling code isn't all that difficult, but I might be insane.
I have an out of process ATL COM server (exe). When it is started by a Client the server spawns a worker thread which polls for some data. Every time the data is updated I want to notify all of the clients with the updated value.
I have created a COM Client, which connects via CoCreateInstanceEx, creates its Sink object, gets the connection point and calls Advise, all without error. However, When the server tries to Fire_event, it's IConnectionPointImpl::m_vec is empty and no clients are ever notified.
I assume this is because the server creates its own object, so I end up with two instances of IConnectionPointImpl::m_vec, one from the server and one from the client when it calls Advise. How can I get the server data to the clients?
I'd recommend this approach. Create a plain vanilla C++ singleton (not a COM object) - let's call it S. S would hold a list of weak, non-AddRef'ed references to all outstanding COM objects (a C++ class pointer, rather than a COM interface pointer, would be convenient). Your COM objects would register themselves with S in their constructor, and deregister in destructor.
When something interesting happens, your worker thread would notify (call a method on) S, which would notify all registered COM objects, which would call Fire_event on themselves.
Be careful when firing events from a worker thread. This is illegal, unless both your main thread and worker thread enter MTA. See http://vcfaq.mvps.org/com/1.htm for details and some workarounds.
I have objects A and B that need to send and receive messages from each other.
For example:
I click, this causes A to send a message to B. B does something with it then sends A another message as a reply.
Right now the way I have it is,
A has a B* and B has an A* and they call each other's sendMessageTo method to communicate.
Is there a better way to do this sort of thing?
Basically, the server sends a message or the local game sends a message which a polymorphic mediator takes in. The mediator either gets the message from the server or local game. The mediator passes it on to the client which does whatever with it. The idea is that the mediator should not be doing logic for the client hence message passing.
I think you need to implement Listener/Observer pattern.
from Wikipedia:
The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
For more ref:
http://en.wikipedia.org/wiki/Observer_pattern
http://www.codeproject.com/KB/cpp/CppEvents.aspx
http://www.codeproject.com/KB/architecture/observer.aspx
I wrote two small C++ applications, one of which is an ActiveX container embedding some ActiveX control. This container application knows the IUnknown* referencing the ActiveX control.
The other application is a client which shall interact with the ActiveX control in the former application. However, I don't know how to get a handle on the control in the client application. Simply transporting the pointer value of the IUnknown* from the server to the client won't work of courses due to independant address spaces.
Is it somehow possible to "duplicate" a handle to some COM object so that the newly created handle can be used by other processes? I'd like to have COM do the RPC work for me. Otherwise, I'd need to do all COM calls in the server application and do all the RPC myself. :-/
You may want to look at RPC in general, and COM Proxies.
A proxy resides in the address space of the calling process and acts as a surrogate for the remote object. From the perspective of the calling object, the proxy is the object. Typically, the proxy's role is to package the interface parameters for calls to methods in its object interfaces. The proxy packages the parameters into a message buffer and passes the buffer onto the channel, which handles the transport between processes. The proxy is implemented as an aggregate, or composite, object. It contains a system-provided, manager piece called the proxy manager and one or more interface-specific components called interface proxies. The number of interface proxies equals the number of object interfaces that have been exposed to that particular client. To the client complying with the component object model, the proxy appears to be the real object.
Greetings all,
I'm trying to implement middleware (driver) for an embedded device with generic communication media layer. Not sure what is the best way to do it so I'm seeking an advice from more experienced stackoverflow users:). Basically we've got devices around the country communicating with our servers (or a pda/laptop in used in field). Usual form of communication is over TCP/IP, but could be also using usb, RF dongle, IR, etc. The plan is to have object corresponding with each of these devices, handling the proprietary protocol on one side and requests/responses from other internal systems on the other.
The thing is how create something generic in between the media and the handling objects. I had a play around with the TCP dispatcher using boost.asio but trying to create something generic seems like a nightmare :). Anybody tried to do something like that? What is the best way how to do it?
Example: Device connects to our Linux server. New middleware instance is created (on the server) which announces itself to one of the running services (details are not important). The service is responsible for making sure that device's time is synchronized. So it asks the middleware what is the device's time, driver translates it to device language (protocol) and sends the message, device responses and driver again translates it for the service. This might seem as a bit overkill for such a simple request but imagine there are more complex requests which the driver must translate, also there are several versions of the device which use different protocol, etc. but would use the same time sync service. The goal is to abstract the devices through the middleware to be able to use the same service to communicate with them.
Another example: we find out that the remote communications with the device are down. So we send somebody out with PDA, he connects to the device using USB cable. Starts up the application which has the same functionality as the timesync service. Again middleware instance is created (on the PDA) to translate communication between application and the device this time only using USB/serial media not TCP/IP as in previous example.
I hope it makes more sense now :)
Cheers,
Tom
The thing is how create something generic in between the media and the handling objects. I had a play around with the TCP dispatcher using boost.asio but trying to create something generic seems like a nightmare :). Anybody tried to do something like that? What is the best way how to do it?
I haven't used Boost, but the way I usually handled that kind of problem was to create a Device base class which the server interacts with, and then subclassed it for each device type, and made the subclasses deal with the device oddness. That way, the Device class becomes a definition of your protocol. Also, the Device class would need to be portable, but the subclasses would not.
If you had to get fancier than that, you could use the Factory pattern to create the actual subclassed objects.
As far as actually communicating, I'd see if I could just run one process per Device. If you have to have more than one Device per process, on Linux I'd just use select() and its friends to manage I/O between the various Device instances. I don't know how to do that on Windows; its select only works for sockets, not serial ports or other file-like things.
Other things that come to mind that might be useful include dbus and the MPI (Message Passing Interface) library, though they aren't complete solutions for your problem (dbus doesn't do inter-computer communications, IIRC).
Does this help at all?
EDIT: Needed a formatted response to Tom's reply...
Does your device class contain the communication specific parts? Because that's the thing I wanted to avoid.
The subclasses contain the communication specific parts. That's the whole point of using subclasses here; the generic stuff goes in the base class, and the specifics go in the subclass.
I was thinking about something like this: Say there is a dispatcher specific for media used which creates Connection object for each connection (media specific), Device obj. would be created as well but just a generic one and the Connection would pass the incoming data to Device and the Device would pass the responses back to Connection.
I think that may be a bit complex, and you're expecting a generic Device to deal with a specific Connection, which can get hard to maintain fast.
What I'd recommend is a Device subclass specifically for handling that type of Connection which takes the Connection from the dispatcher and owns it until the connection closes. Then your manager can talk to the generic Device and the Connection can mess with the specifics.
An example: Say you have a temperature sensor USB thingamajig. You have some dispatcher that catches the "USB thing plugged in" signal. When it sees the USB thing plugged in:
Dispatcher creates a USBTemperatureThingConnection.
Dispatcher creates a USBTemperatureDevice, which is a subclass of Device, giving the USBTemperatureThingConnection to the USBTemperatureDevice as a constructor parameter.
USBTemperatureDevice::USBTemperatureDevice(USBTemperatureThingConnection* conn) goes and sets up whatever it needs locally to finish setting up the Connection, then sends a message to the Device Manager saying it has set itself up.
Some time later, the Device Manager wants to set the time on all devices. So it iterates through its list of devices and calls the generic (maybe even abstract) Device::SetTime(const struct timespec_t&) method on each of them.
When it gets to your temperature device, it calls USBTemperatureDevice::SetTime(const struct timespec_t&), since USBTemperatureDevice overrode the one in Device (which was either abstract, i.e. virtual void SetTime(const struct timespec_t&) = 0; or a no-op, i.e. virtual void SetTime(const struct timespec_t&) {}, so you don't have to override it for devices that can't set time). USBTemperatureDevice::SetTime(const struct timespec_t&) does whatever USB Temperature sensor-specific things are needed, using the USBTemperatureThingConnection, to get the time set.
Some time later, the device might send back a "Time Set Result" message, saying if it worked or not. That comes in on the USBTemperatureThingConnection, which wakes up your thread and you need to deal with it. So your USBTemperatureDevice::DealWithMessageFromSensor() method (which only exists in USBTemperatureDevice) dives into the message contents and figures out if the time setting worked or not. It then takes that result, turns it into a value defined in enum Device::ResultCode and calls Device::TimeSetComplete(ResultCode result), which records the result, sets a flag (bool Device::timeComplete) saying the result is in, and then hits a Semaphore or Condition to wake up the Device Manager and get it to check all the Device's, in case it was blocked waiting for all the devices to finish setting time before continuing.
I have no idea what that pattern is called. If pressed, I'd say "subclassing", or "object-oriented design" if I felt grumpy. The "middleware" is the Device class, the DeviceManager, and all their underlings. The application then just talks to the Device Manager, or at most to the generic Device interface of a specific device.
Btw. Factory pattern was planned, each object would run in separate thread :)
Good to hear.
I'm assuming by TCP/IP you mean remote nodes, and by USB, etc. the local devices connected to the same physical box. I think what I'm missing in your explanation is the part that announces the new local devices to the server process ( i.e. the analog of a listening socket) Again, assuming something along the lines of Linux uevent, I would start with the following structure:
Controller: knows correct time, manages event sources, reacts to events
Event source: produces "new/delete device" events, knows its device class
server socket
local device monitor
etc.
Device class: encapsulates device-specific logic and manages/enumerates devices
remote device type (connected socket)
USB device type
USB device version X.Y.Z type
etc.
The high-level protocol is very simple - on receipt or "new device" event, query the "Device class" for time from given device, then update the time on the device. The "Device class" is the driver/translator/bridge that implements the conversion from query/update interface to device-specific commands (network exchange for remote nodes.) It also holds a list of its devices.
This should easily map to a class diagram. Was there something else that I missed?