qt tcp socket通信实现字符串传输

QTcpServer的基本操作:
1、调用listen监听端口。
2、连接信号newConnection,在槽函数里调用nextPendingConnection获取连接进来的socket。

QTcpSocket的基本能操作:
1、调用connectToHost连接服务器。
2、调用waitForConnected判断是否连接成功。
3、连接信号readyRead槽函数,异步读取数据。
4、调用waitForReadyRead,阻塞读取数据。

服务器端

  1. 新建一个服务器端工程,填入
QT += network
#include<QtNetwork/QtNetwork>
  1. mainwindows.h文件中加入成员
public:
    void init();
private slots:
    void sendMessage(); //发送消息
    void onReciveData();  //接收数据
    void newListen(); //建立tcp监听事件
    void acceptConnection(); //接收客户端连接
    void showError(QAbstractSocket::SocketError); //错误输出
private:
    QTcpSocket *tcpSocket;
    QTcpServer *tcpServer;
   // QTimer *timer;
  1. 函数的定义
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init();

    setWindowTitle(QString::fromLocal8Bit("Server"));
    connect(ui->sendBtn,SIGNAL(clicked(bool)),SLOT(sendMessage()));
}

构造函数中,调用init()函数,当点击了发送按钮就会产生一个槽函数sendMessage,然后直接调用这个槽函数。

void MainWindow::init()
{
   // timer = new QTimer;

    tcpServer = new QTcpServer;
    tcpSocket = new QTcpSocket;
    newListen();
    connect(tcpServer,SIGNAL(newConnection()),SLOT(acceptConnection()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),SLOT(showError(QAbstractSocket::SocketError)));
}

新建一个QTcpServer类的对象,和QTcpSocket类的对象。调用newlisten()监听服务器的socket请求函数,有新的连接的时候,调用acceptConnection()函数,失败的话调用showError()。

void MainWindow::newListen()
{
    if(!tcpServer->listen(QHostAddress::Any,6666))
    {
        qDebug()<<tcpServer->errorString();

        tcpServer->close();
    }
}

QHostAddress::Any 4 双any-address栈,与该地址绑定的socket将侦听IPv4,6666端口。

void MainWindow::acceptConnection()
{
    tcpSocket = tcpServer->nextPendingConnection();
    connect(tcpSocket,SIGNAL(readyRead()),SLOT(onReciveData()));
}

连接成功后,连接信号readyRead(),调用onReciveData()。

void MainWindow::sendMessage()  //发送数据
{
    QString textEdit = ui->lineEdit->text();
    QString strData =QString::fromLocal8Bit("Time: ") + QTime::currentTime().toString() + "\n" + textEdit.toLocal8Bit() + "\n";
    QByteArray sendMessage = strData.toLocal8Bit();
    mChat += ("Send " + sendMessage);
    ui->textEdit->setText(mChat);
    tcpSocket->write(sendMessage);
}

void MainWindow::onReciveData()  //读取数据
{
    QString data = tcpSocket->readAll();
    qDebug()<<data;
    mChat +=("Recv " + data);
    ui->textEdit->setText(mChat);
}

发送数据,获取编辑框中的字符串,发送。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、TCP状态linux查看tcp的状态命令:1)、netstat -nat 查看TCP各个状态的数量2)、lso...
    北辰青阅读 9,528评论 0 11
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 参考:http://www.2cto.com/net/201611/569006.html TCP HTTP UD...
    F麦子阅读 2,978评论 0 14
  • iPhone的标准推荐是CFNetwork 库编程,其封装好的开源库是 cocoa AsyncSocket库,用它...
    Ethan_Struggle阅读 2,283评论 2 12
  • 前言 我们深谙信息交流的价值,那网络中进程之间如何通信,如我们每天打开浏览器浏览网页时,浏览器的进程怎么与web服...
    Chars阅读 3,029评论 2 119