我正在用 C++ 编写客户端,用 Python 编写服务器。
服务器接受来自客户端的连接,并向客户端发送其播放器 ID 号,格式为正则表达式“id\s\d”。 (例如“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))
客户端初始化它的套接字,然后连接。我实现了 connected()
以在 GUI 上显示一条消息(如果它被发出)。它可以毫无问题地发出。服务器端也一样,我收到连接没有问题。
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()));
}
服务器从客户端接收数据没有问题。 是客户端没有正确接收到信息。
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()
返回一个 QString
我把我的问题定位下来,似乎 canReadLine() 永远不会返回 true,因此我永远无法读取它。是什么原因导致的?
最佳答案
这是因为canReadLine()
寻找"\n"
。 Python 不会自动添加它,因此,我的字符串没有行尾。只需在 Python 代码中添加 "\n"
即可解决我的问题。
关于C++ Qt - QTcpSocket 发出 readyRead() 但 canReadLine() 始终为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13236859/