学习自《Qt5.9 C++开发指南》

服务器端: 

QTcpServer *tcpServer; //TCP服务器
tcpServer=new QTcpServer(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));

当有新的客户端接入时,QTcpServer内部的incomingConnection()函数会创建一个与客户端相连的QTcpSocket对象,然后发射信号newConnection()。

tcpSocket = tcpServer->nextPendingConnection(); //创建socket

使用nextPendingConnection()接受客户端的连接,然后使用QTcpSocket与客户端通信。 

    connect(tcpSocket, SIGNAL(connected()),
            this, SLOT(onClientConnected()));

客户端socket连接建立时发射此信号 

void MainWindow::onClientConnected()
{//客户端接入时
    ui->plainTextEdit->appendPlainText("**client socket connected");
    ui->plainTextEdit->appendPlainText("**peer address:"+
                                   tcpSocket->peerAddress().toString());
    ui->plainTextEdit->appendPlainText("**peer port:"+
                                   QString::number(tcpSocket->peerPort()));
}
    connect(tcpSocket, SIGNAL(disconnected()),
            this, SLOT(onClientDisconnected()));

 客户端socket连接断开时发射此信号

void MainWindow::onClientDisconnected()
{//客户端断开连接时
    ui->plainTextEdit->appendPlainText("**client socket disconnected");
    tcpSocket->deleteLater();
    //    deleteLater();//QObject::deleteLater();
}
    connect(tcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(onSocketStateChange(QAbstractSocket::SocketState)));

本程序的socket状态变化时发射此信号

void MainWindow::onSocketStateChange(QAbstractSocket::SocketState socketState)
{//socket状态变化时
    switch(socketState)
    {
    case QAbstractSocket::UnconnectedState:
        LabSocketState->setText("scoket状态:UnconnectedState");
        break;
    case QAbstractSocket::HostLookupState:
        LabSocketState->setText("scoket状态:HostLookupState");
        break;
    case QAbstractSocket::ConnectingState:
        LabSocketState->setText("scoket状态:ConnectingState");
        break;

    case QAbstractSocket::ConnectedState:
        LabSocketState->setText("scoket状态:ConnectedState");
        break;

    case QAbstractSocket::BoundState:
        LabSocketState->setText("scoket状态:BoundState");
        break;

    case QAbstractSocket::ClosingState:
        LabSocketState->setText("scoket状态:ClosingState");
        break;

    case QAbstractSocket::ListeningState:
        LabSocketState->setText("scoket状态:ListeningState");
    }
}
    connect(tcpSocket,SIGNAL(readyRead()),
            this,SLOT(onSocketReadyRead()));

本程序的socket的读取缓冲区有新数据时发射此信号

void MainWindow::onSocketReadyRead()
{//读取缓冲区行文本
//    QStringList   lines;
    while(tcpSocket->canReadLine())
        ui->plainTextEdit->appendPlainText("[in] "+tcpSocket->readLine());
//        lines.append(clientConnection->readLine());
}
    QString     IP=ui->comboIP->currentText();//IP地址
    quint16     port=ui->spinPort->value();//端口
    QHostAddress    addr(IP);
    tcpServer->listen(addr,port);//
//    tcpServer->listen(QHostAddress::LocalHost,port);// Equivalent to QHostAddress("127.0.0.1").

 监听

    if (tcpServer->isListening()) //tcpServer正在监听
    {
        tcpServer->close();//停止监听
    }

停止监听

void MainWindow::on_btnSend_clicked()
{//发送一行字符串,以换行符结束
    QString  msg=ui->editMsg->text();
    ui->plainTextEdit->appendPlainText("[out] "+msg);

    QByteArray  str=msg.toUtf8();
    str.append('\n');//添加一个换行符
    tcpSocket->write(str);
}

客户端:

QTcpSocket  *tcpClient;  //socket
tcpClient=new QTcpSocket(this); //创建socket变量
    QString     addr=ui->comboServer->currentText();
    quint16     port=ui->spinPort->value();
    tcpClient->connectToHost(addr,port);

以异步方式连接到指定IP地址和端口的TCP服务器,连接成功后会发射connected()信号 

    if (tcpClient->state()==QAbstractSocket::ConnectedState)
        tcpClient->disconnectFromHost();

断开socket,关闭成功后发射disconnected()信号 

04-24 06:20