qt socket

来源:互联网 发布:java建造者模式实例 编辑:程序博客网 时间:2024/05/21 14:03

别忘project文件配置中加上socket

pro文件里的配置项当中加入如下的:
QT += network


(1) new a sockey, and then connect to server.

socket=newQTcpSocket(this);

 

 

socket->connectToHost(ip->text(),4200);

 

(2)server 回应后,ui展示连接了。

connect(socket,SIGNAL(connected()),this,SLOT(connected()));//在此函数里面可以实现ui的展示。

void QAbstractSocket::connected () [signal]

This signal is emitted after connectToHost() has been called and a connection has been successfully established.

 

 

(3)client收到server的消息后

connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));

void MainWindows::readyRead()

{

    while(socket->canReadLine())

  {

                   QStringline= QString::fromUtf8(socket->readLine()).trimmed();

        QRegExp  regexp1("^([^:]+):(.*)$");
        QRegExp  regexp2("^/users:(.*)$");
        if(regexp1.indexIn(line)!=1)
        {
           QString msg=regexp1.cap(1);
           。。。。。。。。。。// process msg and update ui.
           
        }
        else if(regexp2.indexIn(line)!=1)
        {
      
          QString user = regexp2.cap(1);
          QStringList info = regexp2.cap(2).split("-");
          QString msg = QTime::currentTime().toString("<font color=blue ><u>hh:mm:ss<u></font>")
                           +" <b>"+user+"</b> : ";
          if(QString(info[1]).compare("B") == 0) msg+="<B>";
          if (QString(info[2]).compare("I") == 0) msg+="<I>";
          if (QString(info[3]).compare("U") == 0) msg+="<U>";
           。。。。。。。。。。// process msg and update ui.
        }

  }

}

eg:

void MainWindow::readyRead()
{
    while(socket->canReadLine())
    {
        QString line = QString::fromUtf8(socket->readLine()).trimmed();
        QRegExp messageRegex("^([^:]+):(.*)$");
        QRegExp usersRegex("^/users:(.*)$");
       
        if(messageRegex.indexIn(line) != -1)
        {
            QString usr = messageRegex.cap(1);
            if(QString(pseudo->text()).compare(usr) == 0){
                sayLineEdit->setText("vous etes bloqu);
                centralWidget()->setEnabled(false);
            }
            screen->append(QTime::currentTime().toString("<u><font color=blue>hh:mm:ss</u></font>")
                           +"<I><font color=red><b> Admin:</b> "+usr+" est bloqu!</font></I>");
        }
        else if(messageRegex.indexIn(line) != -1){
            QString msg = serveurRegex.cap(1);
            screen->append(QTime::currentTime().toString("<u><font color=blue>hh:mm:ss</u></font>")+
                           "<I><font color=green> Serveur : "
                           +msg+"</font></I>");
        }
        else if(debloquerRegex.indexIn(line) != -1){
            QString usr = debloquerRegex.cap(1);
            if(pseudo->text().compare(usr) == 0){
                sayLineEdit->setText("vous etes debloqu);
                centralWidget()->setEnabled(true);
            }
            screen->append(QTime::currentTime().toString("<u><font color=blue>hh:mm:ss</u></font>")+
                           "<I><font color=green><b> Admin:</b> "+usr+" est d閎loqu!</font></I>");
        }
        else if(usersRegex.indexIn(line) != -1)
        {
            usrList->clear();
            QStringList users = usersRegex.cap(1).split(",");
            QString s= "Disponible";
            foreach(QString user, users){
                QStringList info = user.split("-");
                if(QString("0").compare(info[2])==0) s= "";
                else if(QString("1").compare(info[2])==0) s= " (Occup";
                else if(QString("2").compare(info[2])==0) s= " (Hors Ligne)";
                new QListWidgetItem(QPixmap(":/img/avatare/"+info[1]+".png"),info[0]+s, usrList);
            }
        }
        else if(msgPRegex.indexIn(line) != -1)
        {
            QStringList msgP = msgPRegex.cap(1).split("-");
            messagePrivee->setVisible(true);
            setFixedSize(600,600);
            screenP->append( "<b>" + msgP[0] + " : </b>" + msgP[1] );
        }
        else if (messageRegex.indexIn(line) != -1)
        {
            QString user = messageRegex.cap(1);
            QStringList info = messageRegex.cap(2).split("-");
            QString msg = QTime::currentTime().toString("<font color=blue ><u>hh:mm:ss<u></font>")
                           +" <b>"+user+"</b> : ";
            if(QString(info[1]).compare("B") == 0) msg+="<B>";
            if (QString(info[2]).compare("I") == 0) msg+="<I>";
            if (QString(info[3]).compare("U") == 0) msg+="<U>";
            QColor c(QString(info[4]).toInt(),QString(info[5]).toInt(),QString(info[6]).toInt());
            msg+="<font color="+c.name()+" >"+info[0]+"</font>";
            if(QString(info[1]).compare("B") == 0) msg+="</B>";
            if (QString(info[2]).compare("I") == 0) msg+="</I>";
            if (QString(info[3]).compare("U") == 0) msg+="</U>";
            screen->append(msg);
        }
    }
}
 
(4)往serve写东西:
socket->write(QString("type:"+ ui1->text() +"-"ui2->text()+"\n").toUtf8());
 
(5) close
socket->close();
 
(6) error handling
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error()));
void MainWindow::error()
{
    //update UI and close
    QMessageBox::critical(this, "Error", socket->errorString());
    socket->close();
}