简体   繁体   English

Qt:服务器从套接字接收数据

[英]Qt: server receiving data from a socket

I'm using Qt and trying to create a Client - Server connection. 我正在使用Qt并尝试创建客户端 - 服务器连接。 Whenever I click a button in my client application, a socket connects to the server and sends some data. 每当我单击客户端应用程序中的按钮时,套接字就会连接到服务器并发送一些数据。 The problem is I don't know how to receive the data. 问题是我不知道如何接收数据。 These are the slots for my buttons. 这些是我按钮的插槽。

void MainWindow::func_button_one(){
socket->connectToHost("127.0.0.1", 1324);

if(socket->waitForConnected(1000)) {
socket->write("button one has been pressed");
socket->waitForBytesWritten(1000);
}

else {
    qDebug() << "Something terrible seems to have happened.";
}
}

Now, in my server application, I tried something like this. 现在,在我的服务器应用程序中,我尝试过这样的事情。

void MainWindow::newConnection(){
QTcpSocket *socket = server->nextPendingConnection();

socket->waitForReadyRead(1000);
qDebug() << "connection received";
qDebug() << socket->readAll();
socket->close();
}

The connection is all right, because the "connection received" message shows up. 连接没问题,因为显示“已收到连接”消息。 So, how am I supposed to receive the data from the client? 那么,我该如何从客户端接收数据呢? QTcpServer doesn't have any read() function. QTcpServer没有任何read()函数。

The connection is all right, because waitForReadyRead returned 'true', or the connection is not all right, because waitForReadyRead returned false after 1000ms. 连接没问题,因为waitForReadyRead返回'true',或连接不正确,因为waitForReadyRead在1000ms后返回false。 How would you know the difference? 你怎么知道这个区别?

Better work asynchronously with signals. 更好地与信号异步工作。 Connect your socket to 'readyRead()'. 将您的套接字连接到'readyRead()'。 Or at least test the return value of waitForReadyRead. 或者至少测试waitForReadyRead的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM