2017-01-16 235 views
0

我嘗試構建一個使用QT的多線程遊戲服務器,因此,每個客戶端都是基於「QThread」的獨立線程。現在我需要將數據發送到其他客戶端在其他線程)哪些在同一個遊戲室。例如,當房主關閉遊戲房間,遊戲服務器需要發送到「room_closed」消息給其他客戶端偉馳在同SOOM,但有一個錯誤:QSocketNotifier:無法啓用或禁用另一個線程的套接字通知器

QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread

PS:我tryed使用sinals/slots但仍有錯誤:

QObject: Cannot create children for a parent that is in a different thread. (Parent is QNativeSocketEngine(0x161764e8), parent's thread is ClientThread(0x16196f10), current thread is QThread(0x14a17278)

我該怎麼辦?

回答

1

看來你並沒有正確處理QObject和QThreads,Qt抱怨道。

我建議你看看Qt文檔:

的快速指南:

  • QObject中的每個實例都與一個QThread的關聯(QObject::thread())。
  • 您可以使用QObject::moveTothread()更改其關聯的線程,但QObject不能有父項,並且必須從QObject當前與之關聯的線程進行調用。
  • 一些QObject(os子類)具有的功能不能從與它們關聯的線程之外的其他線程調用。這就是爲什麼你有關於QSocketNotifier的第一個錯誤。
  • 你不能從一個線程創建一個QObject,並給它一個與另一個線程關聯的父對象。那是你的第二個錯誤。
+0

服務器的代碼在這裏被引用[link](http://www.bogotobogo.com/Qt/Qt5_QTcpServer_Multithreaded_Client_Server.php),我只是想發送數據到其他客戶端,在不同的線程中,我嘗試使用socket-> moveToThread(QThread :: currentThread());但它顯示了這個QObject :: moveToThread:當前線程(0x16415450)不是對象的線程(0x16415550)。無法移動到目標線程(0x164154450) QSocketNotifier:無法啓用或禁用其他線程的套接字通知器 – tobin

+0

正如我所說的,您需要從QObject所關聯的線程中調用socket-> moveToThread();'。所以'socket-> moveToThread(QThread :: currentThread())'沒有任何意義,因爲這隻有在'socket-> thread()'已經是'QThread :: currentThread()'時纔有效。 –

+0

感謝您的幫助,我不太明白,您能否給我一個例子,遵循[此代碼](http://www.bogotobogo.com/Qt/Qt5_QTcpServer_Multithreaded_Client_Server.php)? – tobin

相關問題