Qtソケット簡単通信
27916 ワード
最近QtのSocket部分を使います。インターネットでこの部分に関する資料はとても複雑です。ここでまとめてみます。Socketの主要部分を取り出して、TCPとUDPの簡単な通信を実現します。
1.UDP通信
UDPには特定のserver端とclient端がありません。簡単に言えば特定のipに対して新聞文を送信するので、それを送信側と受信側に分けます。 注意:proファイルにQT+=networkを追加する場合、Qtのネットワーク機能は使用できません。
1.1.UDP送信端
1.UDP通信
UDPには特定のserver端とclient端がありません。簡単に言えば特定のipに対して新聞文を送信するので、それを送信側と受信側に分けます。 注意:proファイルにQT+=networkを追加する場合、Qtのネットワーク機能は使用できません。
1.1.UDP送信端
#include <QtNetwork>
QUdpSocket *sender;
sender = new QUdpSocket(this);
QByteArray datagram = “hello world!”;
//UDP
sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,6665);
// IP
QHostAddress serverAddress = QHostAddress("10.21.11.66");
sender->writeDatagram(datagram.data(), datagram.size(),serverAddress, 6665);
/* writeDatagram , , -1
qint64 writeDatagram(const char *data,qint64 size,const QHostAddress &address,quint16 port)
qint64 writeDatagram(const QByteArray &datagram,const QHostAddress &host,quint16 port)
*/
1.2.UDP
#include <QtNetwork>
QUdpSocket *receiver;
//
private slots:
void readPendingDatagrams();
receiver = new QUdpSocket(this);
receiver->bind(QHostAddress::LocalHost, 6665);
connect(receiver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));
void readPendingDatagrams()
{
while (receiver->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(receiver->pendingDatagramSize());
receiver->readDatagram(datagram.data(), datagram.size());
// datagram
/* readDatagram
qint64 readDatagram(char *data,qint64 maxSize,QHostAddress *address=0,quint16 *port=0)
*/
}
}
2.TCP
TCP , , server client 。
2.1.TCP client
#include <QtNetwork>
QTcpSocket *client;
char *data="hello qt!";
client = new QTcpSocket(this);
client->connectToHost(QHostAddress("10.21.11.66"), 6665);
client->write(data);
2.2.TCP server
#include <QtNetwork>
QTcpServer *server;
QTcpSocket *clientConnection;
server = new QTcpServer();
server->listen(QHostAddress::Any, 6665);
connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
void acceptConnection()
{
clientConnection = server->nextPendingConnection();
connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readClient()));
}
void readClient()
{
QString str = clientConnection->readAll();
//
char buf[1024];
clientConnection->read(buf,1024);
}
:wuyuan Wuyuan's Blog , ! : http://wuyuans.com/2013/03/qt-socket/
・