码迷,mamicode.com
首页 > 其他好文 > 详细

qt tcp 通信实例

时间:2017-05-31 19:00:07      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:about   dwr   lin   end   null   window   write   服务端   success   

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->socket = new QTcpSocket(this);
}
void MainWindow::on_pushButton_2_clicked(){
    this->socket->close();
}
void MainWindow::on_pushButton_clicked(){
    this->socket->connectToHost("127.0.0.1",80000,QTcpSocket::ReadWrite);
    connect(this->socket,SIGNAL(connected()),this,SLOT(connected()));
}
void MainWindow::connected(){
    QMessageBox::about(this,"notice","connect successful");
    connect(this->socket,SIGNAL(readyRead()),this,SLOT(readyread()));
}
void MainWindow::readyread(){
    QMessageBox::about(this,"notice","ready read");
    QByteArray arr = this->socket->readAll();
    QDataStream *des = new QDataStream(&arr,QIODevice::ReadOnly);//重点
    QString str1;
    QString str2;
    (*des)>>str1>>str2;
    qDebug()<<str1+str2;
    QMessageBox::about(this,"x",str1+str2);

}

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

  服务端

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTcpServer>
#include <QTcpSocket>
#include <QMessageBox>
#include <QByteArray>
#include <QString>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->socket = nullptr;
    this->server = new QTcpServer(this);
    this->server->listen(QHostAddress::Any,80000);
    QObject::connect(this->server,SIGNAL(newConnection()),this,SLOT(newConnect()));
}
void MainWindow::newConnect(){
    this->socket = this->server->nextPendingConnection();
    QMessageBox::about(this,"notice","new connect");
    connect(this->socket,SIGNAL(readyRead()),this,SLOT(ReceiveData()));
}
void MainWindow::ReceiveData(){
    QByteArray arr = this->socket->readAll();
    QDataStream dst(arr);
    QString str1;
    QString str2;
    dst>>str1>>str2;
    qDebug()<<str1<<str2;
}
void MainWindow::on_pushButton_clicked(){
    QString str = this->ui->lineEdit->text();
    QByteArray arr;
    QDataStream dst(&arr,QIODevice::ReadWrite);
    dst<<QString("message:")<<str;
    this->socket->write(arr);
}
void MainWindow::on_pushButton_2_clicked(){
    this->socket->close();
}

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

  

qt tcp 通信实例

标签:about   dwr   lin   end   null   window   write   服务端   success   

原文地址:http://www.cnblogs.com/first-semon/p/6925185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!