2016-09-26 61 views
1

我尝试从客户机通过行foreach循环发送字符串服务器产品线:如何通过QTcpSocket发送和读取字符串行?

foreach(QString s, stringlist) 
    client.sendMessage(s); 

但客户只收到第一个字符串。当我从字符串中删除“\ n”时,服务器接收到一串合并成一个大字符串的字符串。我认为添加“\ n”会将数据分成字符串,我可以用readLine()来阅读。我错过了什么?

我的客户

class cClient:public QTcpSocket 
{ 
public: 
    void sendMessage(QString text) 
    { 
     text = text + "\n"; 
     write(text.toUtf8());   
    } 
}; 

和服务器:

class pServer:public QTcpServer 
{ 
    Q_OBJECT 
public: 
    pServer() 
    { 
     connect(this,SIGNAL(newConnection()),SLOT(slotNewConnection())); 
    } 

public slots: 
    void slotNewConnection() 
    { 
     QTcpSocket* c = nextPendingConnection(); 
     connect(c,SIGNAL(readyRead()),this, SLOT(readData())); 
    } 

    void readData() 
    { 
     QTcpSocket* conn = qobject_cast<QTcpSocket*>(sender()); 
     QString data = QString(conn->readLine()); 
    } 
}; 

回答

3

你可能会收到多条线路的时间,但只有在阅读的第一个。通过检查canReadLine来阅读尽可能多的行。类似的东西:

void readData() 
{ 
    QTcpSocket* conn = qobject_cast<QTcpSocket*>(sender()); 
    QStringList list; 
    while (conn->canReadLine()) 
    { 
     QString data = QString(conn->readLine()); 
     list.append(data); 
    }  
} 
+0

谢谢!这正是我错过的。现在一切正常! – lena