QTcpSocket QTcpServer 类的使用方法

SERVER.cpp

server::server(QWidget *parent) :
    QDialog(parent)
{
    setupUi(this);
    connect(this->startButton,SIGNAL(clicked()),this,SLOT(start()));
    connect(this->serverButton,SIGNAL(clicked()),this,SLOT(sendMessage()));

}

void server::start()
{
    tcp_server=new QTcpServer(this);
    tcp_server->listen(QHostAddress::Any,8888);
    connect(tcp_server,SIGNAL(newConnection()),this,SLOT(newConnect()));
}
void server::sendMessage()
{
    QByteArray send=this->servertEdit->toPlainText().toUtf8();
    socket->write(send,send.length());
}
void server::newConnect()
{
    socket=tcp_server->nextPendingConnection();
    connect(socket,SIGNAL(readyRead()),this,SLOT(readMessage()));
}

void server::readMessage()
{
    QByteArray array=socket->readAll();
    QString text=QString::fromUtf8(array);
    this->servertEdit->setText(text);
}

Client.cpp

Client::Client(QWidget *parent) :
    QMainWindow(parent)
{
    setupUi(this);
    connect(this->connectButton,SIGNAL(clicked()),this,SLOT(connectHost()));
    connect(this->clientButton,SIGNAL(clicked()),this,SLOT(sendMessage()));
}

void Client::connectHost()
{
    socket=new QTcpSocket(this);
    socket->connectToHost("127.0.0.1",8888);
    connect(socket,SIGNAL(readyRead()),this,SLOT(readMessage()));
}
void Client::sendMessage()
{
    QString text=this->clientEdit->toPlainText();
    //socket->setLocalAddress(QHostAddress("192.168.1.1"));
    //QString data=socket->localAddress().toString();
    socket->write(text.toUtf8(),text.length());
}
void Client::readMessage()
{
    QString text=QString::fromUtf8(socket->readAll());
    this->clientEdit->setText(text);
}


你可能感兴趣的:(QTcpSocket QTcpServer 类的使用方法)