QTcpSocket、QTcpServer基本用法

英文注释都是从Qt助手里面抄的,英语不好,就不翻译了。
在启动程序的时候,要先启动服务端,然后再启动客户端才能建立连接,如果先启动客户端,再启动服务端,就连接不上了。
我是想在客户端开一个死循环一直检测是否连接成功,然后不停的连接,直到连上,跳出循环,这样就算先启动客户端也可以连接上。
Client:

//widget.h
#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();
    void initUi(); //初始化界面
    void newTcpConnect(); //创建新的连接
private slots:
    void sendMessage(); //发送消息
    void receiveMessage(); //接收消息
private:
    QTextEdit *myEdit,*yourEdit;
    QPushButton *sendButton,*closeButton;
    QHBoxLayout *hlayout;
    QVBoxLayout *vlayout,*alllayout;

    QTcpSocket *tcpSocket;
};

#endif // WIDGET_H


//widget.cpp
#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    initUi();
    connect(sendButton,SIGNAL(clicked(bool)),this,SLOT(sendMessage()));
    connect(closeButton,SIGNAL(clicked(bool)),this,SLOT(close()));
    tcpSocket = new QTcpSocket;
    newTcpConnect();
    //This signal is emitted once every time new data is available for reading from the device.
    connect(tcpSocket,SIGNAL(readyRead()),SLOT(receiveMessage()));
}

Widget::~Widget()
{
    delete tcpSocket;
}


void Widget::initUi()
{
    this->resize(500,500);
    this->setWindowTitle("Client");

    sendButton = new QPushButton("send",this);
    closeButton = new QPushButton("close",this);
    myEdit = new QTextEdit(this);
    yourEdit = new QTextEdit(this);

    hlayout = new QHBoxLayout;
    hlayout->addStretch(6);
    hlayout->addWidget(closeButton);
    hlayout->addWidget(sendButton);

    vlayout = new QVBoxLayout;
    vlayout->addWidget(yourEdit,2);
    vlayout->addWidget(myEdit,1);

    alllayout = new QVBoxLayout;
    alllayout->addLayout(vlayout);
    alllayout->addLayout(hlayout);

    this->setLayout(alllayout);
}

void Widget::newTcpConnect()
{
    //Aborts the current connection and resets the socket.
    //Unlike disconnectFromHost(), this function immediately closes the socket, discarding any pending data in the write buffer.
    tcpSocket->abort();
    //Attempts to make a connection to hostName on the given port.
    tcpSocket->connectToHost("127.0.0.1",9999);

}

void Widget::sendMessage()
{
    QString str = myEdit->toPlainText();
    yourEdit->append(str);
    myEdit->clear();
    QByteArray data = str.toUtf8();
    tcpSocket->write(data);
}

void Widget::receiveMessage()
{
    //Reads all remaining data from the device, and returns it as a byte array.
    QByteArray data = tcpSocket->readAll();
    QString str(data);
    yourEdit->append(str);
}

Server:

//widget.h
#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();
    void initUi(); //初始化界面
    void newListen(); //建立tcp监听事件
private slots:
    void acceptConnect(); //接受客户端连接
    void sendMessage(); //发送消息
    void receiveMessage(); //接收消息
private:
    QTextEdit *myEdit,*yourEdit;
    QPushButton *sendButton,*closeButton;
    QHBoxLayout *hlayout;
    QVBoxLayout *vlayout,*alllayout;

    QTcpServer *tcpServer;
    QTcpSocket *tcpSocket;
};

#endif // WIDGET_H


//widget.cpp
#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    initUi();
    tcpSocket = new QTcpSocket;
    tcpServer = new QTcpServer;
    newListen();
    //This signal is emitted every time a new connection is available.
    connect(tcpServer,SIGNAL(newConnection()),SLOT(acceptConnect()));
    //This signal is emitted after an error occurred.
    //The socketError parameter describes the type of error that occurred.
    connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(close()));
}

Widget::~Widget()
{
    delete tcpSocket;
    delete tcpServer;
}

void Widget::initUi()
{
    this->resize(500,500);
    this->setWindowTitle("Server");

    sendButton = new QPushButton("send",this);
    closeButton = new QPushButton("close",this);
    myEdit = new QTextEdit(this);
    yourEdit = new QTextEdit(this);

    connect(sendButton,SIGNAL(clicked(bool)),this,SLOT(sendMessage()));
    connect(closeButton,SIGNAL(clicked(bool)),this,SLOT(close()));

    hlayout = new QHBoxLayout;
    hlayout->addStretch(6);
    hlayout->addWidget(closeButton);
    hlayout->addWidget(sendButton);

    vlayout = new QVBoxLayout;
    vlayout->addWidget(yourEdit,2);
    vlayout->addWidget(myEdit,1);

    alllayout = new QVBoxLayout;
    alllayout->addLayout(vlayout);
    alllayout->addLayout(hlayout);

    this->setLayout(alllayout);
}

void Widget::newListen()
{
    //Tells the server to listen for incoming connections on address address and port port.
    //If port is 0, a port is chosen automatically. If address is QHostAddress::Any, the server will listen on all network interfaces.
    if(!tcpServer->listen(QHostAddress::Any,9999))
    {
        qDebug()<errorString();
        tcpServer->close();
    }
}

void Widget::acceptConnect()
{
    //Returns the next pending connection as a connected QTcpSocket object.
    tcpSocket = tcpServer->nextPendingConnection();
    connect(tcpSocket,SIGNAL(readyRead()),SLOT(receiveMessage()));
}

void Widget::sendMessage()
{
    QString str = myEdit->toPlainText();
    yourEdit->append(str);
    myEdit->clear();
    QByteArray data = str.toUtf8();
    tcpSocket->write(data);
}

void Widget::receiveMessage()
{
    QByteArray data = tcpSocket->readAll();
    QString str(data);
    yourEdit->append(str);
}

你可能感兴趣的:(Qt学习)