我有python在本地网络代码上发送简单的字符串如下:
import socket
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
stringTosend = ("Hello,World")
print(stringTosend)
sock.connect(('192.168.2.39', 42207))
try:
sock.sendall(stringTosend)
except socket.error:
print 'Send failed'
sys.exit()
print'Sent'
在我的QT中,我设置了标签,显示“Helloworld” 我能在qt做什么? 谢谢
答案 0 :(得分:0)
使用Qt时,您应该遵循事件驱动架构。 Qt的事件循环应始终准备好receive new events。通常,您可以将插槽连接到任何QObject
的信号,以获得特定事件发生的通知,并且您的插槽应包含该信号触发时运行的代码。
从Qt5开始,您还可以连接到C++11 lambdas(而不是插槽)。我已经利用它来使代码尽可能小。请注意,在实际项目中,您可能需要将其分成不同的类,每个类都有自己的责任,以使事情更易于维护。 。
#include <QtCore>
#include <QtNetwork>
#include <QtWidgets>
int main(int argc, char* argv[]) {
QApplication a(argc, argv);
//the label to show received string
QLabel label("no connection yet");
//tcp server object to listen for incoming connections
QTcpServer tcpServer;
//connect the server's newConnection signal to get notified for new connections
QObject::connect(&tcpServer, &QTcpServer::newConnection, [&tcpServer, &label] {
//get a new tcp socket for the incoming connection
QTcpSocket* socket = tcpServer.nextPendingConnection();
//change the label to reflect the new state
label.setText("received connection");
//connect the socket's readyRead signal to get notified
//when data is available on the socket
QObject::connect(socket, &QTcpSocket::readyRead, [socket, &label] {
//receive available data from the socket
QByteArray received = socket->readAll();
//change label's text (assuming text is encoded using UTF-8)
label.setText(QString::fromUtf8(received));
//close and delete the socket when done
socket->close();
socket->deleteLater();
});
});
//start listening on port 42207
if(!tcpServer.listen(QHostAddress::Any, 42207))
label.setText("server listen error");
//show the label
label.show();
//start event loop
return a.exec();
}