我用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,因此我永远无法读取它。什么可能导致这种情况?
答案 0 :(得分:1)
这是因为canReadLine()
寻找"\n"
。 Python不会自动添加它,因此,我的字符串没有行尾。只需在Python代码中添加"\n"
即可解决我的问题。