cpp:
cpp
server = new QTcpServer(this);
connect(server, &QTcpServer::newConnection, this, &PythonConsole::newConnection);
if (!server->listen(QHostAddress::Any, 8000)) {
qWarning("Unable to start the server: %s", qPrintable(server->errorString()));
}
调试:
cpp
connect(server, &QTcpServer::newConnection, [this]() {
QTcpSocket *socket = server->nextPendingConnection();
qDebug() << "New connection from:" << socket->peerAddress().toString();
});
cpp
void PythonConsole::newConnection()
{
clientConnection = server->nextPendingConnection();
connect(clientConnection, &QTcpSocket::readyRead, this, &PythonConsole::readClient);
}
void PythonConsole::readClient()
{
QByteArray data = clientConnection->readAll();
QString command = QString::fromUtf8(data);
runSource(command);
clientConnection->close();
}
h:
cpp
QTcpServer *server;
QTcpSocket *clientConnection;