不多说了,学长给的项目中用到了,不得不学习一下不然就是一脸懵逼啊~

先贴上代码:

/*TcpClient*/
#include "tcpclient.h"
#include <QPushButton>
#include <QLineEdit>
#include <QHBoxLayout>

TcpClient::TcpClient(QWidget *parent) : QWidget(parent)
{
    this->setWindowTitle("TcpClient");

    bt = new QPushButton("send");
    edit = new QLineEdit();

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(edit);
    layout->addWidget(bt);

    this->setLayout(layout);

    socket = new QTcpSocket;
    socket->connectToHost("127.0.0.1", 9988);

    connect(bt, SIGNAL(clicked(bool)), this, SLOT(slotbuttonclicked()));
    connect(edit, SIGNAL(returnPressed()), this, SLOT(slotbuttonclicked()));  //回车按下
}

void TcpClient::slotbuttonclicked()
{
    QString s = edit->text();
    if(s.isEmpty())  //为空不发送
    {
        return;
    }
    socket->write(s.toUtf8());   //发送
    edit->clear();  //清空
}

这是客户端,首先是建立一个socket对象,然后调用其connectToHost成员函数去连接Server.
之后通过按钮单击去执行槽函数,通过write函数去发送.

#include "tcpserver.h"
#include <QTextBrowser>
#include <QVBoxLayout>

TcpServer::TcpServer(QWidget *parent) : QWidget(parent)
{
    browser = new QTextBrowser(this);

    this->setWindowTitle("TcpServer");

    server = new QTcpServer;

    server->listen(QHostAddress::Any, 9988); //任意主机, 端口9988

    connect(server, SIGNAL(newConnection()), this, SLOT(slotnewconnection()));

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(browser);
    this->setLayout(layout);
}

void TcpServer::slotnewconnection()
{
    while (server->hasPendingConnections())
    {
        socked = server->nextPendingConnection();
        connect(socked, SIGNAL(readyRead()), this, SLOT(slotreadytoread()));
    }
}

void TcpServer::slotreadytoread()
{
    while(socked->bytesAvailable() > 0)
    {
         QByteArray buf = socked->readAll();
         browser->append(buf);
    }
}

类似,先建立一个TcpServer,然后监听端口,有新连接时,通过newConnection()信号调用槽函数,槽函数中的循环是因为如果发送数据不止一个但是只调用一次槽函数,就会丢失数据,所以用循环来判断.假如能读取了,通过readyRead()信号调用槽函数,将数据附加到browser去即可.

测试结果:
test.png

最后修改:2019 年 06 月 30 日
如果觉得我的文章对你有用,请随意赞赏