資源簡介
使用QT編寫tcp的簡單服務端。能夠同時連接多個客戶端,很基礎的實現,適合對Qt tcpsever 不太了解的小伙伴學習。代碼僅供參考。
代碼片段和文件信息
#include?“MyTcpServer.h“
#include?
#include?
Server::Server(Qobject?*parent?int?port):QTcpServer(parent)
{
??????qDebug()<<“>>>>start?to?listen...“;
??????listen(QHostAddress::Any?port);?//監聽
}
void?Server::incomingConnection(int?socketDescriptor)
{
????qDebug()<<“>>>>a?new?client?connect“;
????TcpSocket?*tcpclientsocket?=?new?TcpSocket(this);//只要有新的連接就生成一個新的通信套接字
????//將新創建的通信套接字描述符指定為參數socketdescriptor
????tcpclientsocket->setSocketDescriptor(socketDescriptor);
????//將這個套接字加入客戶端套接字列表中
????tcpclientsocketlist.append(tcpclientsocket);
????//接收到tcpclientsocket發送過來的更新界面的信號
????connect(tcpclientsocket?SIGNAL(updateserver(QStringint))?this?SLOT(slotupdateserver(QStringint)));
????connect(tcpclientsocket?SIGNAL(clientdisconnected(int))?this?SLOT(slotclientdisconnect(int)));
}
void?Server::slotupdateserver(QString?msg?int?length)
{
????//將這個信號發送給界面
????emit?updateserver(msg?length);
????//將收到的信息發送給每個客戶端從套接字列表中找到需要接收的套接字
????for(int?i?=?0;?i?????{
????????QTcpSocket?*item?=?tcpclientsocketlist.at(i);
//????????if(item->write((char*)msg.toUtf8().data()?length)?!=?length)
//????????{
//????????????continue;
//????????}
????????item->write(msg.toUtf8().data());
????}
}
void?Server::slotclientdisconnect(int?descriptor)
{
????qDebug()<<“>>>>client?disconnect!!!“;
???for(int?i?=?0;?i????{
????????QTcpSocket?*item?=?tcpclientsocketlist.at(i);
????????if(item->socketDescriptor()?==?descriptor)
????????{
????????????tcpclientsocketlist.removeAt(i);//如果有客戶端斷開連接,?就將列表中的套接字刪除
????????????qDebug()<<“>>>>client?delet“;
????????????return;
????????}
????}
?return;
}
int?Server::SendData(QByteArray?&arr)
{
????qDebug()?<“>>>>>SendSerialData:“<????int?ret;
????for(int?i?=?0;?i?????{
????????QTcpSocket?*item?=?tcpclientsocketlist.at(i);
????????ret?=item->socketDescriptor();
????????QHostAddress?s=item->localAddress();
????????QString?Ipadd?=?s.toString();
????????qDebug()<<“>>>>ip?address:“<
????????item->write((arr));
????????item->flush();
????}
????qDebug()?<“>>>>>ret:“< ????if(ret?0)
????{
????????qDebug()?<“>>>>>SendData?failed:“;
????????return?-1;
????}
????return?ret;
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件???????2638??2018-10-08?15:08??TCP服務端代碼\MyTcpServer.cpp
?????文件????????789??2018-10-08?09:50??TCP服務端代碼\MyTcpServer.h
?????文件???????1149??2018-10-08?09:48??TCP服務端代碼\TcpSocket.cpp
?????文件????????639??2018-10-08?09:50??TCP服務端代碼\TcpSocket.h
?????目錄??????????0??2018-10-10?10:41??TCP服務端代碼
-----------?---------??----------?-----??----
?????????????????5215????????????????????5
- 上一篇:Commix(ModBus)
- 下一篇:智能垃圾桶
評論
共有 條評論