qt之tcp

1、需要在pro里添加network


2、qtcpserver qtcpsocket
    tcp客户端
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(connectedInt()));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedInt()));

    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));  //接收到数据
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
    客户端连接函数
    tcpSocket->abort();
    tcpSocket->connectToHost(lineEditHost->text(), lineEditPort->text().toInt());
客户端读取数据
QDataStream in(tcpSocket); //这里数据已经在in里了,读取的时候数据类型一定要移植,否则会出错
    in.setVersion(QDataStream::Qt_4_7);
    if(blockSize == 0)
    {
        if(tcpSocket->bytesAvailable() < (int)sizeof(quint16))
            return;
        in >> blockSize;
    }
    if(tcpSocket->bytesAvailable() < blockSize)
        return;
    in >> message;
    labelReceive->setText(message);

3、服务器端
tcpServer = new QTcpServer; //建立服务器
    if(!tcpServer->listen(QHostAddress::LocalHost, 6666)) //绑定端口号,监听
    {
        qDebug() << tcpServer->errorString();
        close();
    }
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendMessage())); //有新连接时调用槽函数
槽函数
void Widget::sendMessage()
{
    static int i;
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);  //熟悉qdatastream的使用,另外,tcp发送数据是以QbyteArray格式来的
    out.setVersion(QDataStream::Qt_4_7);
    out << (quint16)0;
    out << tr("Hello guy!");
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();  //为新连接创建一个tcpsocket
    connect(clientConnection, SIGNAL(disconnected()), clientConnection,
            SLOT(deleteLater()));
  //  clientConnection->disconnectFromHost();
  //  clientConnection->connectToHost();
    clientConnection->write(block); //发送数据
    clientConnection->disconnectFromHost(); //发完数据断开连接, 我觉得这时候对方收到断开连接的时候,应该调用tcp_close关闭连接
    lineEdit->setText(tr("one message has been sended!") + QString("%1").arg(i));
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值