![](/img/trans.png)
[英]Writing to QTcpSocket does not always emit readyRead signal on opposite QTcpSocket
[英]C++ Qt - QTcpSocket emit readyRead() but canReadLine() always false
我正在用C ++編寫客戶端,並用Python編寫服務器。
服務器接受來自客戶端的連接,並將其播放器ID號發送給客戶端,該播放器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"
解決我的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.