QT 多線程和 QSocket 網(wǎng)絡(luò)編程實(shí)例解析
本文介紹的是QT 多線程和 QSocket 網(wǎng)絡(luò)編程實(shí)例解析,要實(shí)現(xiàn)網(wǎng)絡(luò)編程,不說這么多,先來看內(nèi)容。
(1) 帶后綴-mt的庫才是支持多線程的.
例如windows下面的qt-mt320.lib,其他平臺libqt-mt
(2)編譯問題,要添加QT_THREAD_SUPPORT
(30針對線程里面而言,blocking(阻塞的) = synchronous(同步的 )
non-blocking (非阻塞的) = asynchronous(異步的 )
而Qt的signal/slot的事件機(jī)制都是基于主程序的線程的,因此所有的事件都是阻塞型的(blocking),也就是說除非你處理完某個slot事件,不然不會有下個事件被觸發(fā)。
(4)QSocket,QSocketNotifier不能和QThread一起使用
- QSocket is for non-blocking IO, it uses some polling like poll() or select() internally and notifies the actual code by emitting signals.
- So QSocket is for use with only the event loop thread, for example in a client with only one socket or a server with very few connections.
- If you want a threaded approach use QThread and QSocketDevice.
- Put one SocketDevice into listening mode and on accept() create a Handler Thread for the socket file descriptor.
- Use the second QSocketDevice constructor to initialise the Connection's socket device instance.
- The server does
- bind()
- listen()
- and
- accept()
- When accept returns it has the filedescriptor of the connection's socket which you can pass to another QSocketDevice constructor.
- The client does connect() to establish the connection.
- Both use readBlock/writeBlock/waitForMore to transfer data
.
一個例子:
(1)用VC6.0新建個Win32 Console Application工程
(2)Project Settings里面Link標(biāo)簽頁面添加qtmain.lib qt-mt320.lib
Project Settings里面C/C++標(biāo)簽頁面添加QT_THREAD_SUPPORT
(3)源代碼文件(main.cpp):
- #include <qthread.h>
- class MyThread : public QThread
- {
- public:
- virtual void run();
- };
- void MyThread::run()
- {
- for( int count = 0; count < 20; count++ )
- {
- sleep( 1 );
- qDebug( "Ping!" );
- }
- }
- int main()
- {
- MyThread a;
- MyThread b;
- a.start();
- b.start();
- a.wait();
- b.wait();
- }
注釋:
This will start two threads, each of which writes Ping! 20 times to the screen and exits.
The wait() calls at the end of main() are necessary because exiting main() ends the program,
unceremoniously killing all other threads.
Each MyThread stops executing when it reaches the end of MyThread::run(),
just as an application does when it leaves main().
小結(jié):關(guān)于QT 多線程和 QSocket 網(wǎng)絡(luò)編程實(shí)例解析的內(nèi)容介紹到這,希望本文對你有所幫助。