我正在用 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,因此我永远无法阅读它。是什么原因造成的?