QT多執行緒伺服器 客戶端

2021-10-05 10:12:24 字數 3401 閱讀 1637

客戶端效果展示

.h

#ifndef dialog_h

#define dialog_h

#include

#include

#include

#include

"timeserver.h"

#include

class

dialog

:public qdialog

;#endif

// dialog_h

.cpp

#include

"dialog.h"

#include

#include

dialog::

dialog

(qwidget *parent)

:qdialog

(parent)

label1-

>

settext(tr

("伺服器端口:%1.").

arg(timeserver-

>

serverport()

));//獲得埠

}dialog::

~dialog()

void dialog::

slotshow()

.h

#ifndef timeserver_h

#define timeserver_h

#include

class

dialog

;class

timeserver

:public qtcpserver

;#endif

// timeserver_h

.cpp

#include

"timeserver.h"

#include

"timethread.h"

#include

"dialog.h"

timeserver::

timeserver

(qobject*parent)

:qtcpserver

(parent)

void timeserver::

incomingconnection

(qintptr socketdescriptor)

//客戶端連線

.h

#ifndef timethread_h

#define timethread_h

#include

#include

#include

class

timethread

:public qthread

;#endif

// timethread_h

.cpp

#include

"timethread.h"

timethread::

timethread

(qintptr socketdescriptor,qobject *parent)

:qthread

(parent)

,socketdescriptor1

(socketdescriptor)

void timethread::

run(

) qbytearray block;

qdatastream out

(&block,qiodevice::writeonly)

; out.

setversion

(qdatastream::qt_5_10)

; uint time2u=qdatetime::

currentdatetime()

.totime_t()

;//轉換為uint型可以在網路中傳輸

out<

tcpsocket.

write

(block)

; tcpsocket.

disconnectfromhost()

;//斷開連線

tcpsocket.

waitfordisconnected()

;//等待返回訊息

}

.h

#ifndef timeclient_h

#define timeclient_h

#include

#include

#include

#include

#include

#include

#include

class

timeclient

:public qdialog

;#endif

// timeclient_h

.cpp

#include

"timeclient.h"

#include

#include

#include

#include

#include

timeclient::

timeclient

(qwidget *parent)

:qdialog

(parent)

timeclient::

~timeclient()

void timeclient::

enablegetbtn()

void timeclient::

gettime()

void timeclient::

readtime()

datetimeedit-

>

setdatetime

(qdatetime::

fromtime_t

(time2u));

//將uint型轉換成qdatetime

getbtn-

>

setenabled

(true);

}void timeclient::

showerror

(qabstractsocket::socketerror socketerror)

//報錯

getbtn-

>

setenabled

(true);

}

每當有乙個客戶端連線時便開啟乙個新執行緒返回當前時間,返回完畢後,自動退出執行緒。

多執行緒程式設計例項 伺服器客戶端簡單通訊

這是乙個非常簡單的通訊程式,不需要什麼前奏來說明這個問題,可以直接來看程式的實現,首先是伺服器端的程式 int main int argc,char argv slisten socket af inet,sock stream,ipproto ip if slisten socket error ...

linux下多執行緒tcp伺服器 客戶端程式

編譯命令 gcc wall g o server server.c lpthread include include include include include include include include include include define port 8458 define max...

Python多執行緒實現客戶端 伺服器模式TCP通訊

這裡是你每次的輸入都會被客戶端讀到,然後傳送給伺服器,伺服器接收到後,回送接收到的資訊並附加上時間戳,客戶端接收到回送訊息後列印訊息到螢幕上。上面的明顯可以看到每個訊息下面都有乙個附加上時間的相同的訊息,這個訊息就是伺服器傳送回來的訊息,沒有帶時間的訊息就是我們輸入的訊息,也是客戶端傳送給伺服器的訊...