一、伺服器
1、宣告乙個qtcpserver物件
qtcpserver* serverlistener;
2、new出物件
this->serverlistener = new qtcpserver();
3、伺服器監聽
qhostaddress ipaddress(「192.168.1.1」);
quint16 ipport = 8080;
serverlistener->listen(ipaddress,ipport);
4、宣告乙個qlist物件用於存客戶端
qlistclientlist;
5、連線訊號與槽
qobject::connect(this->serverlistener,signal(newconnection()),this,slot(newconnection()));//newconnection是自定義槽函式,用於管理clientlist列表
6、實現newconnection函式,儲存客戶端至clientlist
void tcpserver::newconnection()
qtcpsocket* serverclient = this->serverlistener->nextpendingconnection();//new出客戶端物件
qobject::connect(serverclient,signal(readyread()),this,slot(rcvdata()));//當此客戶端有資料時在自定義rcvdata函式裡接收
qobject::connect(serverclient,signal(disconnected()),this,slot(removeclient()));//當此客戶端斷開連線時,會發出disconnected訊號,在自定義removeclient裡去除客戶端
7、實現removeclient函式,去除客戶端
void tcpserver::removeclient()
for(int i=0;iclientlist.length();i++)
if(clientlist.at(i)->socketdescriptor() == -1)//用於判斷當前客戶端是否有效
clientlist.removeat(i);
8、實現rcvdata函式,接收資料
void tcpserver::rcvdata()
qbytearray ba;
for(int i=0;iclientlist.length();i++)
9、傳送資料
clientlist.at(n)->write(qbytearray ba);
10、停止
serverlistener->close();
二、客戶端
1、宣告乙個qtcpsocket物件
qtcpsocket* tcpclient;
2、new出物件
this->tcpclient = new qtcpsocket();
3、連線伺服器,連線訊號與槽
tcpclient->connecttohost("192.168.1.1","8080");
qobject::connect(this->tcpclient,signal(readyread()),this,slot(rcvdata()));//rcvdata是自定義接收槽函式
4、實現rcvdata函式,接收資料
void tcpclient::rcvdata()
qbytearray ba = tcpclient->readall();
5、傳送資料
tcpclient->write(qbytearray ba);
6、關閉
tcpclient->close();
ps:軟體開發流程
Qt下TCP程式設計
一 伺服器 1 宣告乙個qtcpserver物件 qtcpserver serverlistener 2 new出物件 this serverlistener new qtcpserver 3 伺服器監聽 qhostaddress ipaddress 192.168.1.1 quint16 ippo...
Qt下Tcp傳輸檔案
ifndef serverwidget h define serverwidget h include include 監聽套接字 include 通訊套接字 include include namespace ui class serverwidget public qwidget endif s...
QT基於tcp協議網路程式設計
基於qt網路程式設計 基於tcp協議 c s模式程式設計 所需要的類 qtcpserver qtcpsocket 利用qt基於tcp協議編寫c s模式程式 兩個類中的訊號 qtcpserver newconnection qtcpsocket readyread connected disconne...