How to use chat rooms QT5 (b) the preparation of a written protocol using TCP a TCP client

Foreword

For server-side client end, it is relatively simple (server-side can view my previous text) on the server side is divided into two functions: 1. establish a connection to the server 2. send data to the server socket word

Implementation

1. Establish a connection to the server-side

First we have to know with whom to establish a connection, so we need a QHostAddress target object to test whether we enter ip address to use, and then use the object to use a QTcpSocket connectToHost () function to establish a connection with the target, the function accepts two parameters, the first parameter is the ip address, the second parameter is the port. when using the function, the server will be able to listen to our access.

2. socket to send data to the server

Variables is the inverse of the read data wirte () function can be realized this operation, wirte () function is called by the object QTcpSocket likewise, the function accepts two parameters, the first parameter is a stored data so transmitted , so that the second parameter is the number of bytes sent.

Specific code

The following code in the .cpp part of the code, the code reference << Qt5 development and examples (third edition) >> If there is error correction understanding would like to present

TcpClient::TcpClient(QWidget *parent,Qt::WindowFlags f)
    : QDialog(parent,f)
{
    //界面初始化
    setWindowTitle(tr("TCP Client"));
    contentListWiget = new QListWidget;
    sendLineEdit = new QLineEdit;
    sendBtn = new QPushButton(tr("Send out"));
    userNameLabel = new QLabel(tr("user name:"));
    userNameLineEdit = new QLineEdit;
    serverIPLabel = new QLabel(tr("The server address:"));
    serverIPLineEdit = new QLineEdit;
    portLabel = new QLabel(tr("port "));
    portLineEdit = new QLineEdit;
    enterBtn = new QPushButton(tr("enter the chat room"));
    mainLayout = new QGridLayout(this);
    mainLayout->addWidget(contentListWiget,0,0,1,2);
    mainLayout->addWidget(sendLineEdit,1,0);
    mainLayout->addWidget(sendBtn,1,1);
    mainLayout->addWidget(userNameLabel,2,0);
    mainLayout->addWidget(userNameLineEdit,2,1);
    mainLayout->addWidget(serverIPLabel,3,0);
    mainLayout->addWidget(serverIPLineEdit,3,1);
    mainLayout-> addWidget (portLabel, . 4 , 0 ); 
    mainLayout -> addWidget (portLineEdit, . 4 , . 1 ); 
    mainLayout -> addWidget (enterBtn, . 5 , 0 , . 1 , 2 ); 

    Status = to false ; // Status indicates the current state, true that has entered the chat room, false leave the IM indicates 
    port = 8010 ; // port to the server is consistent 
    portLineEdit-> the setText (QString :: Number (port)); 
    serverIP = new new QHostAddress (); // initialize a QHostaddress objects
    Connect (enterBtn, the SIGNAL (clicked ()), the this , the SLOT (slotEnter ())); 
    Connect (sendBtn, the SIGNAL (clicked ()), the this , the SLOT (slotSend ())); 
    sendBtn -> setEnabled ( to false ); 
} 

the TcpClient :: ~ the TcpClient () 
{ 

} 

void the TcpClient :: slotEnter () 
{ 
    IF (! Status) 
    { 
        QString IP = serverIPLineEdit-> text (); // get the address of the text box 
        IF (serverIP-> the setAddress (! ip)) // will get the name and address to verify 
        { 
            QMessageBox :: Information ( the this , TR ( "error"),tr("server ip address error!"));
            return;
        }
        if(userNameLineEdit->text()=="")
        {
            QMessageBox::information(this,tr("error"),tr("User name error"));
            return;
        }
        userName = userNameLineEdit->text();
        tcpSocket = new QTcpSocket(this);//初始化一个QTcpSocket的对象
        Connect (TCPsocket, the SIGNAL (connected ()), the this , the SLOT (slotConnected ())); // After successful connection when connected () signals 
        Connect (TCPsocket, the SIGNAL (disconnected ()), the this , the SLOT (slotDisconnected () )); // if () signaling connection is disconnected disconnected 
        (TCPsocket, the sIGNAL (the readyRead (connect)), the this , the SLOT (DateReceived the ())); // update a text box when the content server returns information 
        TCPsocket -> the connectToHost (* serverIP, port); // build the target ip, connection port 
        Status = to true ; 
    } 
    the else {
         int length = 0 ; 
        QString MSG = the userName + TR ( ": Leave chat room " );
         IF ((length = tcpSocket-> Write (msg.toLatin1 (), msg.length ())) = msg.length ())! // The Leave chat room server to a string 
        {
             return ; 
        } 
        TCPsocket -> disconnectFromHost (); // try to close a socket 
        Status = to false ; 
    } 
} 
void the TcpClient :: slotConnected () // received signal after the connection is successful, sends "Enter chat room" string to server 
{ 
    sendBtn -> setEnabled ( to true ); 
    enterBtn -> the setText (TR ( " Leave " ));
    int length = 0 ; 
    QString MSG = the userName + TR ( " the Enter Chat Room " );
     IF (! (length = tcpSocket-> Write (msg.toLatin1 (), msg.length ())) = msg.length ()) 
    { 
        return ; 
    } 
} 
void the TcpClient :: slotSend () // when reading the text box and press the send key transmits the content to the server 
{
     iF (sendLineEdit-> text () == "" ) 
    { 
        return ; 
    } 
    QString MSG = + the userName " : " + sendLineEdit-> text (); 
    TCPsocket ->Write (msg.toLatin1 (), msg.length ()); 
    sendLineEdit -> Clear (); 
} 
void the TcpClient :: slotDisconnected () // Once disconnected the connection button is pressed again able 
{ 
    sendBtn -> setEnabled ( to false ); 
    enterBtn -> the setText ( " the Enter Chat Room " ); 
} 
void the TcpClient :: DateReceived The () // read the data transmitted by the server when the message update a text box 
{
     the while (tcpSocket-> the bytesAvailable ()> 0 ) { 
        the QByteArray Datagram; 
        datagram.resize (TCPsocket -> the bytesAvailable ()); 
        TCPsocket ->read(datagram.data(),datagram.size());
        QString msg = datagram.data();
        contentListWiget->addItem(msg.left(datagram.size()));
    }
}

 

Guess you like

Origin www.cnblogs.com/Emiya-Shirou/p/11279928.html