[英]C++ Qt - QTcpSocket emit readyRead() but canReadLine() always false
I am writing a client in C++ and a server in Python. 我正在用C ++编写客户端,并用Python编写服务器。
The server accepts the connection from the client, and sends to the client its player ID number, formated for the regular expression "id\\s\\d". 服务器接受来自客户端的连接,并将其播放器ID号发送给客户端,该播放器ID号的格式为正则表达式“ id \\ s \\ d”。 (eg "id 3")
(例如“ id 3”)
if s is serversocket:
print "Listening..."
if accept_connection or nb_player < 5:
connection, client_address = s.accept();
print 'New connection from ', client_address
connection.setblocking(0)
inputs.append(connection)
# Send player I to new connection
connection.send("id "+str(len(inputs)-1))
The client initializes its socket, and connect. 客户端初始化其套接字,然后连接。 I implemented
connected()
to display a message on the GUI, if it is emitted. 我实现了
connected()
以在GUI上显示消息(如果已发出)。 It is emitted without problem. 它发出没有问题。 Same thing on the server side, I receive the connection without issues.
在服务器端也是如此,我收到的连接没有问题。
Window::Window(QWidget *parent) :
QDialog(parent),
ui(new Ui::Window)
{
ui->setupUi(this);
/* Initialize socket */
socket = new QTcpSocket(this);
socket->connectToHost("localhost", 13456);
connect(socket, SIGNAL(readyRead()), this, SLOT(data_received()));
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
}
The server receives data from the client without problem. 服务器从客户端接收数据没有问题。 It is the client that does not receive the information correctly.
客户端无法正确接收信息。
void Window::data_received(){
QRegExp id_re("id\\s(\\d)");
while (socket->canReadLine()){
/* Read line in socket (UTF-8 for accents)*/
ui->log->append("listening...");
QString line = QString::fromUtf8(socket->readLine()).trimmed();
/* Player ID returned by server */
if ( id_re.indexIn(line) != -1){
//Test
ui->log->append("The ID arrived");
//Extract ID
QString id_str = id_re.cap(1);
//Put in data structure of player
player->set_player_id(id_str);
//Display message
ui->log->append(QString("You are Player "+ player->get_player_id()));
}
}
}
get_player_id()
returns a QString
get_player_id()
返回一个QString
I targeted my problem down, and it seems that canReadLine() is never returning true, therefore I can never read it. 我将问题定位为目标,并且似乎canReadLine()永远不会返回true,因此我永远无法读取它。 What could cause that?
是什么原因造成的?
It is because canReadLine()
looks for "\\n"
. 这是因为
canReadLine()
寻找"\\n"
。 Python does not automatically add it, therefore, there was no end-of-line to my string of character. Python不会自动添加它,因此,我的字符串中没有行尾。 Simply adding
"\\n"
in the Python code solved my problem. 只需在Python代码中添加
"\\n"
解决我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.