Recently to use the socket part of QT, online about this part of the data are more complex, I summed up in this, the main part of the socket out to achieve the TCP and UDP simple communication.
1.UDP communication UDP does not have a specific server side and client side, simply to send a message to a specific IP, so I divide it into the sender and the receiver side.
Note: You will not be able to use Qt's network features in the. Pro file if you want to add qt + = Networks。 1.1.UDP Send End
#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 Receiving End
#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 communication TCP Words to complicate points, you must first establish a connection to transfer data, divided into server and client side. 2.1.TCP Client Side
#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 Side
#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 This article from Wuyuan ' s Blog reprint please specify, thank you! Article Address: Http://wuyuans.com/2013/03/qt-socket
"Go" Qt Socket simple Communication