【问题标题】:how to listen to a specific port in qt using QTcpSocket? [duplicate]如何使用 QTcpSocket 监听 qt 中的特定端口? [复制]
【发布时间】:2014-04-08 07:17:16
【问题描述】:

我正在使用 QTcpSocket 在两个应用程序之间进行通信。一个是c++程序,另一个是PHP编写的网页。

目标是使用套接字将数据从我的网页发送到我的 c++ 程序。

我不知道如何在特定端口上打开连接,例如 12345,如果我有任何数据,我不知道如何监听它..

到目前为止,我已经编写了以下代码:

MainWindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    Mysocket = new QSocket(this);
    Mysocket->Initialization();
}

MainWindow::~MainWindow()
{
    delete ui;
}

QSocket.cpp

#include "qsocket.h"
#define SOCKET_PORT 12345
QSocket::QSocket(QObject *parent) :
    QObject(parent)
{
}


void QSocket::Initialization()
{
    //connected
    socket = new QTcpSocket(this);
    socket->connectToHost("localhost",SOCKET_PORT);
    connect(socket,SIGNAL(connected()),this,SLOT(connected()));
    connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()));
    connect(socket,SIGNAL(bytesWritten(qint64)),this,SLOT(bytesWritten(qint64)));
    connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));
    if(!socket->waitForConnected(1000))
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(0,"Error","Error in Socket Connection",
                                        QMessageBox::Yes|QMessageBox::No);
        socket->close();
    }
    socket80->close();
}
void QSocket::connected()
{
        QMessageBox::StandardButton reply;
        int PortNumber = socket->localPort();
        reply = QMessageBox::question(0,"Connected","Socket Connection is Established",
                                        QMessageBox::Yes|QMessageBox::No);

        qDebug()<<"I'm Listening to Port: "<<PortNumber<<"on the local host \n";
}

void QSocket::disconnected()
{
    qDebug()<<"Disconnected .... \n";
    socket->close();
}

void QSocket::bytesWritten(qint64 bytes)
{
        qDebug()<<"We wrote "<<bytes<<" \n";
}

void QSocket::readyRead()
{
    qDebug()<<"Reading .... \n";
    qDebug()<<socket->bytesAvailable();
    qDebug()<<socket->readAll();
}

当我运行这段代码时,它不会打开任何连接并给出错误,它会进入这个 if 语句..

if(!socket->waitForConnected(1000))
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(0,"Error","Error in Socket Connection",
                                    QMessageBox::Yes|QMessageBox::No);
    socket->close();
}

如果我将端口号更改为 80,它可以正常工作,并且所有功能都可以正常工作。 通过阅读 SO 中的一些帖子,我意识到一个解决方案是使用 QTcpServer,但我没有任何具体的经验。 这里有什么问题?!

附言

我的平台规格。

Ubuntu 13.10

Qt 5.2.1

【问题讨论】:

  • 我认为您需要QTcpServer 及其QTcpServer::listen() 功能。一旦你获得新的连接,newConnection 信号就会被发出,你需要处理它来创建一个新的数据传输套接字。

标签: c++ qt sockets ubuntu


【解决方案1】:

您可以使用以下示例服务器。您可以通过调用 start_listen(int port_no) 开始监听端口。

#include <QtNetwork>
#include <QMessageBox>

class server : public QTcpServer {
    Q_OBJECT
public:
    explicit server(QObject *parent = 0);
    ~server();
    QTcpSocket server_socket;
public slots:
    void tcpReady();
    void tcpError( QAbstractSocket::SocketError error );
    bool start_listen(int port_no);
protected:
    void incomingConnection( int descriptor );
};

server::server(QObject *parent) : QTcpServer(parent) {
    connect( &server_socket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(tcpError(QAbstractSocket::SocketError)) );
    connect( &server_socket, SIGNAL(readyRead()),
             this, SLOT(tcpReady()) );
    server_socket.setSocketOption(QAbstractSocket::KeepAliveOption, true );
}

server::~server() {
    server_socket.disconnectFromHost();
    server_socket.waitForDisconnected();
}

void server::tcpReady() {
    QByteArray array = server_socket.read(erver_socket.bytesAvailable());
}

void server::tcpError(QAbstractSocket::SocketError error) {
    QMessageBox::warning( (QWidget *)this->parent(), tr("Error"),tr("TCP error: %1").arg( server_socket.errorString() ) );
}

bool server::start_listen(int port_no) {
    if( !this->listen( QHostAddress::Any, port_no ) ) {
        QMessageBox::warning( (QWidget *)this->parent(), tr("Error!"), tr("Cannot listen to port %1").arg(port_no) );
    }
    else
        return true;
}

void server::incomingConnection(int descriptor) {
    if( !server_socket.setSocketDescriptor( descriptor ) ) {
        QMessageBox::warning( (QWidget *)this->parent(), tr("Error!"), tr("Socket error!") );
        return;
    }
}

【讨论】:

  • ..感谢您的回答..我还没有测试您的代码,但在收听之前是否需要在端口上打开连接?我们一般可以监听任何端口吗?或者我需要在我的 c++ 程序中打开该端口才能使用它?
  • 如果答案是肯定的,那怎么办?如何在 qt 中为 qtcpserver 对象打开一个端口?
  • 通过调用listen,你实际上是在打开一个端口并监听它,等待有人连接你。当有人连接时,将调用incomingConnection 函数并通过调用setSocketDescriptor 并传递描述符来建立连接,之后您可以通过QTCPSocket 进行通信。
  • 还有一件事......如果我使用listen方法开始连接,我是否必须先向我的客户发送一些东西才能得到任何东西,或者没有必要? qtcpserver 中具体的函数在端口上写什么?
  • 当你调用listen时,你应该等到客户端连接你调用incomingConnection。要写入数据,您应该使用 QTcpSocket 对象的 write 方法,例如: server_socket.write( someBytes );
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2011-06-28
  • 2011-09-14
相关资源
最近更新 更多