Qt简单实现Tcp通信

开发环境:Ubuntu 16.04

语言:C++

服务器程序:

#include "dialog.h"
#include "ui_dialog.h"
#include <QtNetwork>
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    tcpServer=new QTcpServer(this);
    if(!tcpServer->listen(QHostAddress::LocalHost,6666))
    {
        qDebug()<<tcpServer->errorString();
        close();
    }
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage()));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::sendMessage()
{
    QByteArray block;
    QDataStream out(&block,QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);//版本号要与客户端一致
    out<<(quint16)0;//预留两个字节,之后会存放实际数据的字节大小
    out<<tr("hello tcp!!");
    out.device()->seek(0);//定位到开始处
    out<<(quint16)(block.size()-sizeof(quint16));
    QTcpSocket *clientConnection=tcpServer->nextPendingConnection();//获取连接的套接字
    connect(clientConnection,SIGNAL(disconnected()),clientConnection,SLOT(deleteLater()));//当连接断开,自动删除该套接字
    clientConnection->write(block);//发送数据
    clientConnection->disconnectFromHost();//一直等待数据发送完毕,然后关闭该套接字,发射disconneted信号
    ui->tcpserverLabel->setText("send data sucessfully!");
}

客户端程序:

#include "dialog.h"
#include "ui_dialog.h"
#include <QtNetwork>
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    tcpSocket=new QTcpSocket(this);
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
    connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
    connect(ui->connectPushButton,SIGNAL(clicked()),this,SLOT(newConnect()));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::newConnect()
{
    blockSize=0;
    tcpSocket->abort();
    tcpSocket->connectToHost(ui->hostLineEdit->text(),ui->portLineEdit->text().toInt());//从界面获取地址和端口号
}

void Dialog::readMessage()
{
    QDataStream in(tcpSocket);
    in.setVersion(QDataStream::Qt_4_0);//版本号与服务器端一致
    if(0==blockSize)//表示刚开始收到数据
    {
        if(tcpSocket->bytesAvailable()<(int)sizeof(quint16))    return;//如果还没收到开头2个字节,则返回.这2个字节就是数据总字节数
        in>>blockSize;//收到两个字节了,将数据总字节数赋值给blockSize
    }
    if(tcpSocket->bytesAvailable()<blockSize)   return;//如果还没收到全部数据,则返回
    in>>message;//收到全部数据
    qDebug()<<message;
    ui->messageLabel->setText(message);//显示
}

void Dialog::displayError(QAbstractSocket::SocketError)
{
    qDebug()<<tcpSocket->errorString();
}

运行效果:

客户端中输入主机和端口号,点击连接:


此项目工程下载地址:
https://download.csdn.net/download/qq_30483585/10469420

猜你喜欢

转载自blog.csdn.net/qq_30483585/article/details/80636174