該示例演示了在本地主機上的tcp客戶端和伺服器是如何通訊的。繫結訊號槽。
連線到伺服器。connect
(&tcpclient,
&qabstractsocket::connected,
this
,&dialog::starttransfer)
;/* 連線到伺服器時回送訊息給伺服器 */
connect
(&tcpclient,
&qiodevice::byteswritten,
this
,&dialog::updateclientprogress)
;/* 繫結寫資料到伺服器的訊號槽 */
這裡比較有意思的是,客戶端連線到伺服器->客戶端(tcpclient)觸發starttransfer槽函式->呼叫tcpclient.
connecttohost
(qhostaddress::localhost, tcpserver.
serverport()
);
tcpclient.write
->觸發qiodevice::byteswritten
訊號->觸發updateclientprogress槽函式呼叫->就一直tcpclient.write
,直到if條件不成立後後停止傳送。void dialog::
starttransfer()
繫結訊號槽用於新連線:void dialog::
updateclientprogress
(qint64 numbytes)
監聽客戶端連線。connect
(&tcpserver,
&qtcpserver::newconnection,
this
,&dialog::acceptconnection)
;
服務端新連線到來:!tcpserver.
islistening()
&&!tcpserver.
listen
()
接收來自客戶端的資料:void dialog::
acceptconnection()
connect
(tcpserverconnection,
&qiodevice::readyread,
this
,&dialog::updateserverprogress)
;/* 接受客戶端資料的槽函式 */
connect
(tcpserverconnection,
qoverload<:socketerror>
::of
(&qabstractsocket::error)
,this
,&dialog::displayerror)
;/* 錯誤反饋 */
connect
(tcpserverconnection,
&qtcpsocket::disconnected,
tcpserverconnection,
&qtcpsocket::deletelater)
;/* 斷開反饋 */
serverstatuslabel-
>
settext(tr
("accepted connection"))
; tcpserver.
close()
;}
TCP伺服器 客戶端程式
server tcpserver.cpp檔案 include common initsock.h include cinitsock initsock 初始化winsock庫 int main 填充sockaddr in結構 sockaddr in sin sin.sin family af ine...
伺服器和客戶端 tcp通訊
在vs2013的環境下,伺服器 如下 include include stdafx.h include pragma comment lib,ws2 32.lib using namespace std define buffer rev 1024 define buffer send 1024 i...
TCP伺服器 客戶端 全部集合
include include include pragma comment lib,ws2 32.lib int main closesocket socket 0 closesocket socket 1 wsacleanup 釋放 初始化 if getchar 如果有輸入則關閉程式 else ...