Qt is a very flexible and versatile library. In one of my previous blog entry I had described how is it possible to create simple GUIs with Qt. If you are not very familiar with Qt, you may like to view my previous blog entry on Qt where in I have put up a short tutorial for Qt. That blog entry can be accessed here : Qt Beginners Tutorial.
In this post we are going to have a look at how it is possible to write a network program in Qt. I am going to demonstrate you how to write a simple TCP Client and a simple TCP Server. I assume that you are familiar with Qt and have atleast some experience with Qt. Especially you understand Qt terminologies like signals & slots. Further, I also assume you are familiar with using Qt Assistant to follow the documentations and know more of the functionality.
QTcpSocket is used as the TCP socket in Qt. It’s used both in client and server side.
To perform as a client, following steps are used:
a) call QTcpSocket.connectToHost() to connect to a server;
b) when connected, QTcpSocket.connected() will be emitted;
c) communicate with the server with QTcpSocket.read() and QTcpSocket.write()
In Qt, the class QTcpServer is used as a TCP server. Generally, the following steps are used:
a) call QTcpServer.listen() to start listening;
b) QTcpServer.newConnection() signal will be emitted when a new connection comes;
c) call QTcpServer.nextPendingConnection() to get the socket object (QTcpSocket) connecting to the client.
d) To communicate with the client you need to use this newly created socket and not the QTcpServer socket. The socket created in 1. is only used for listening.