您的位置:首页 > 理论基础 > 计算机网络

Qt开发:TCP和UDP网络通信

2015-06-13 23:13 911 查看
【原文】http://wuyuans.com/2013/03/qt-socket/

这篇文章简洁清晰



TCP

客户端

#include <QtNetwork>
QTcpSocket *client;
char *data="hello qt!";
client = new QTcpSocket(this);
client->connectToHost(QHostAddress("10.21.11.66"), 6665);
client->write(data);

服务端

#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);
}


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)
*/


服务端

#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)
*/
}
}

注意

只是简单的收发功能,其中服务器和客户端收发的API是一样的
可以获取所连接的IP和port,未写
可以绑定其他的信号槽,比如disconnect,未写
udp发送不一定要广播,可以指定ip和端口
以上代码需要添加到h和cpp的合适位置
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: