Qt网络编程:QTcpSocket使用示例

QTcpServer

    tcpServer = new QTcpServer(this);
    connect(tcpServer, &QTcpServer::newConnection, this, &Dialog::sendData);
    connect(tcpServer, &QTcpServer::acceptError, this, &Dialog::displayError);
​​​​​​​    tcpServer->listen(QHostAddress::Any, 8888);
void Dialog::sendData()
{
    qDebug() << "连接成功,尝试向客户端写入数据";
    QString sWriteData = "来自tcp服务端的数据";
    //获取与客户端通信的socket
    QTcpSocket* oneTcpSocket = tcpServer->nextPendingConnection();
    //从客户端读数据
    QString sReadData = oneTcpSocket->readAll();
    oneTcpSocket->write(sWriteData.toUtf8());
    //与客户端断开连接
// 	connect(oneTcpSocket, &QTcpSocket::disconnected, oneTcpSocket, &QTcpSocket::deleteLater);
// 	oneTcpSocket->disconnectFromHost();
}

void Dialog::displayError(QAbstractSocket::SocketError socketError)
{
    qDebug() << "服务端错误消息:" << socketError;
}

QTcpSocket

    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, &QTcpSocket::connected, this, &Dialog::connected);
    connect(tcpSocket, &QIODevice::readyRead, this, &Dialog::readyRead);
    typedef void (QAbstractSocket::*QAbstractSocketErrorSignal)(QAbstractSocket::SocketError);
    connect(tcpSocket, static_cast<QAbstractSocketErrorSignal>(&QTcpSocket::error), this, &Dialog::error);
    tcpSocket->connectToHost(QHostAddress::LocalHost/*"127.0.0.1"*/, 8888);
    tcpSocket->waitForReadyRead();
void Dialog::readyRead()
{
    qDebug() << "客户端读取信息:" << QString(tcpSocket->readAll());
}

void Dialog::connected()
{
    qDebug() << "客户端连接成功";
}

void Dialog::error(QAbstractSocket::SocketError socketError)
{
    qDebug() << "客户端错误信息:" << socketError;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值