如何通过 QTcpSocket 发送和读取字符串行?
How to send and read string lines via QTcpSocket?
我尝试在 foreach 循环中逐行将字符串从客户端发送到服务器:
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());
}
};
您当时可能收到不止一行,但只读了第一行。通过检查 canReadLine 阅读尽可能多的可用行。类似的东西:
void readData()
{
QTcpSocket* conn = qobject_cast<QTcpSocket*>(sender());
QStringList list;
while (conn->canReadLine())
{
QString data = QString(conn->readLine());
list.append(data);
}
}
我尝试在 foreach 循环中逐行将字符串从客户端发送到服务器:
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());
}
};
您当时可能收到不止一行,但只读了第一行。通过检查 canReadLine 阅读尽可能多的可用行。类似的东西:
void readData()
{
QTcpSocket* conn = qobject_cast<QTcpSocket*>(sender());
QStringList list;
while (conn->canReadLine())
{
QString data = QString(conn->readLine());
list.append(data);
}
}