Qt does not know accept for socket programming - qt

If I press a button, a network server should get started. But it seems the compiler does not know the right accept-function. This line:
sockConnection = accept(hSocket, &remoteAddr, &iRemoteAddrLen);
gets this error:
no matching function for call to 'NetConf::accept(SOCKET&, sockaddr_in*, socklen_t*)'
It appears that the accept-function is part of a Qt Object and not the socket one I would like to use. I read about including "socket.h" but cant find it on my system (Windows 7 - 64 bit, Qt library 4.8.6). Any suggestions?

Qt is a framework that abstracts away the requirement for calling low level functions such as accept.
If you want a TCP-based network server, start with a QTcpServer class object and call its listen function
If you've connected a QObject's slot to the QTcpServer's newConnection signal, you'll be notified when a connection is made.
Once notified of a new connection, you then call nextPendingConnection which returns a QTcpSocket, which you can use to communicate with the client by using its available functions as described in the Qt docs for this class.

Related

How should I really use QLocalSocket and QLocalServer?

Qt example about using QLocalSocket/QLocalServer for IPC is not that clear as it should be.
I have arrived (after a lot of what-if ideas) to next conclusions:
Sockets for windows named pipes are designed to deliver one message at a time. It can not be used in continuous for never-ending data stream as pipe stores all data sent inside regardless if it was read or not causing huge memory waste. So basic use-case looks like: reciever connects to pipe -> sender sends one frame of data -> someone of them close socket hanlde until reciever wants more (and again new connection must be established)
QLocalSocket cannot be saved as instance. This is confusing. First connection is done perfectly. I create a receiver class with QLocalSocket within. I connect this socket to named pipe and read data. I close the socket (on the sender side) and connect it again to the pipe to read next data frame. Server sees the new connection, but once I try to write into - "Socket is closing" error appears. Looks like some data is remaining (may be HANDLE to windows socket is saved from previous connection).
With Process Explorer I've found that socket is connected only within my function inside class (slot with only `connectToServer' function), but once control is returned to Qt event loop - connection to named pipe disappears before server has any possibility to write into it. Once again: this happens only second time, if the socket has ever been closed. If I delete socket and create new one (on the heap) - it works like it should.
There are some problems with detection if QLocalSocket is valid while one side is closed unexpectedly.
This happens when I force close receiver executable after connection has been established. Server has already stored pointer to socket but it is no more valid. Looks like isValid() or other methods from QLocalSocket could help me, but they fail too. In practice when client is forced closed QLocalSocket instance on sender side still exists, but has messed up private implementation: in qiodevice.cpp : 1607 where CHECK_WRITABLE(write, qint64(-1)); is performed d_ptr is not valid pointer anymore and has something like 0xafafafaf. Looks like private implementation is controlled outside Qt event loop causing this to happen.
So. After all said. It looks like I am doing something wrong. So how do QLocalSocket should really be used for never-ending data stream in cases when client must receive data as soon as it exists?
UPD: please find code example here. Also note socket_by_instance branch to understand my second note.
Some notes about the code: Let's say I have some data stream incoming on once every 10 ms that I must process on the sender side (in any case) and sent it to receiver(s) if it(they) exists.
What I do not like in this code is that on the receiver side I need to do new/deleteLater for every socket connection (100 times per second). Knowing that receiver always has one connection and it is always opened and always connected to one the same socket - I think this is waste of time doing new/delete here. Please look at socket_by_instance branch to see my try to avoid this issue.

Move QTcpSocket to a new Thread after the connection is initiated

I've got a threaded server.
QTcpSocket needs to be created on the thread it needs to be ran on, FI: Qt - Handle QTcpSocket in a new thread by passing the socket descriptor.
My problem is that, I need to have a pool of thread and move the socket on a specific thread AFTER the client has sent a specific token which defines on which thread the socket needs to be.
In other words, I need to read the socket to know on which thread to place it beforehand.
Some idea would be to bind first to a QTcpSocket, read, then send the descriptor to the thread and create another QTcpSocket but the doc says:
Note: It is not possible to initialize two abstract sockets with the
same native socket descriptor.
Another solution is to create the socket in a separated thread and then join both thread together, though I don't know if that is possible.
Or perhaps be able to read the socket descriptor on the main thread before calling setSocketDescriptor on the child thread, if that is even possible?
You can absolutely easily move sockets across QThreads, just pay attention to four things:
1) Make sure your QTcpSocket does not have parent before you move
2) Disconnect everything from socket object before move
3) Connect anything you need back in a function which is running in a destination thread (you may use some sort of pool in a thread there those 'moved' objects stored before thread pick them up
4) Call readAll() after init as you may miss some readyRead() signals
Don't see any reasons not to do this if that fits design, at least I used it many times for multithreaded services to split sockets handlers across cores.

Query on RMI working

I don't get one thing in RMI. It's a bit confusing actually.
On client side, we have the business interface (Hello.class), the client code (HelloClient.class) and the remote stub (probably Hello_stub.class) and on server side we have the server code (HelloImpl.class), the business interface (Hello.class) and the skeleton .
For Java 5 onwards, we don't create stubs but still they are c=in picture i believe.
So, how does the communication happen ?
The client calls method on Hello.class which then calls Hello_stub.class for all n/w operations. The Hello_stub.class calls the skeleton which then calls Hello.class and then calls methods on HelloImpl.class ?
I am a bit confused after reading Head first EJB :) .It would be glad if someone clarified it.
When the stub's method is called:
It gets a TCP connection to s target out of the client connection pool, or creates one if there isn't a pooled connection
Bundles up the call and the arguments into a serializable object.
Writes the object to the connection along with some other stuff like a JRMP protocol header and a remote objectID.
Reads the reply object from the connection.
Returns the connection to the pool, where it gets closed after a certain idle time.
If the reply object is an exception, throws it.
Otherwise returns the reply object as the method result.
At the server, a thread sits on the listening socket, accepting connections, creating threads, and dispatching incoming remote calls to the correct remote object via the specified object ID.
This is done via reflection. RMI skeletons haven't been used since 1998, except in the case of stubs you deliberately generate with rmic -v1.1, but the principle is the same either way.

selective D-BUS signal emitting from ObServer (unicast signal)

I have a situation where I have a single ObServer object and a set of Clients.
ObServer and clients connected through D-BUS (IPC). ObServer has generic interface for all clients. But, time to time ObServer needs to notify clients about some events. Clients listen for a ObServer Generic interface signal OnNotify().
Question:
How to emit D-BUS signal (OnNotify()) from ObServer to specified client (instead of broadcast to all) ?
p.s
Qt D-BUS used for wrapping but any approach are welcome.
You can't. Signals are received by all clients that have registered for that signal on a DBus interface.
You can either add a parameter to the OnNotify signal, and handle it in the client, or create separate signals for each client. However, if you want this component to be dynamic (add clients at runtime), you have to go with the first approach (parameter to OnNotify).
EDIT: more information on signals
A signal is defined as follows:
A signal in DBus consists of a single message, sent by one process to any number of other processes. That is, a signal is a unidirectional broadcast. The signal may contain arguments (a data payload), but because it is a broadcast, it never has a "return value." Contrast this with a method call (see the section called “Calling a Method - Behind the Scenes”) where the method call message has a matching method reply message.
The emitter (aka sender) of a signal has no knowledge of the signal recipients. Recipients register with the bus daemon to receive signals based on "match rules" - these rules would typically include the sender and the signal name. The bus daemon sends each signal only to recipients who have expressed interest in that signal.
Original source.
EDIT: updated answer in light of Dmitry's comments.
Filtering dbus signals will not work with any of the current available bindings (didn't check all of them, only 2 (dbus-cpp and qt), so anyone can follow up on this).
However it is possible to set the DESTINATION field in the header of the dbus message, using a function that is available in the dbus interface (dbus-message.h):
dbus_bool_t dbus_message_set_destination (DBusMessage *message, const char *destination)
In case of QT bindings, you have to modify the bindings as follows: in qdbusmessage.cpp in the method
DBusMessage *QDBusMessagePrivate::toDBusMessage(const QDBusMessage &message, QDBusError *error)
on the case branch DBUS_MESSAGE_TYPE_SIGNAL you need to make a call to q_dbus_message_set_destination.
Also the destination must be available from the upper layers. Easiest way would be to extend the QDBusMessage class in order to retain the destination, and then pass it below to the dbus layer.
If you are able to modify the QT bindings in your project, then you might do such a maneuver :).

Keep TCP connection persistent even after sub-routine calling connect() is end. How?

I have an application that calls connect() in a subroutine A.
This sub-routine A is called when a button A is pressed.
After connection has established, user can choose to click button B.
This button B has to be programmed as a separate sub-routine.
However, I need TCP connection to run sub-routine B.
After connect() is called in sub-routine A, sub-routine A is exit.
The connection is closed as well during exit.
Is there any way to keep this connection after connected even sub-routine A is exit?
Many thanks!
what programming you are using? Anyway you can have the socket fd & the socket struct defined in public to make it persistent across the routines or have them as parameter of the subroutine. I would expect more code to answer more precisely.
Actually I am using objective-C programming for iPhone. However, the content are written in C. I copied and modified the sample code from internet. I am getting quite some problem with the code written.
Then, I found sample code in Objective-C language, It solved the problem. The connection can be kept alive. The sample code is from here:
http://www.devx.com/wireless/Article/43551/1954
This program connect to network automatically once application is running without having user to click any connect button. This might be just fine. Now, it is time to figure out how to add a button so that user can disconnect from the network anytime.

Resources