带有QList的C ++多客户端TCP服务器

时间:2016-03-28 15:54:04

标签: c++ qt tcp qlist

必要的信息:

  QList<QTcpSocket*> list;
  QTcpServer* server;
  QTcpSocket* socket;

在Qt中,我构建了一个TCP-Server( QTcpServer )!我的所有连接客户端都有一个 QList ,我想亲自阅读每个客户端的输入数据。因此,如果 QTcpServer 获得新连接,我会这样说:

void Server::newConnection()
{
   qDebug() << "New Connection";
   list.append(server->nextPendingConnection());
   connect(list.last(),SIGNAL(readyRead()),this,SLOT(readyRead()));
}

如何在 SLOT QList 之外),该客户端发送 SIGNAL readyRead() > readyRead()

void Server::readyRead(){
       //??
}

欢迎任何帮助!

3 个答案:

答案 0 :(得分:3)

你试过QObject :: sender()吗?它应该返回实际发送信号的QObject的实例。希望这会有所帮助。

答案 1 :(得分:2)

解决方案:

void Server::readyRead(){

    QByteArray buffer;
    QTcpSocket* readSocket = qobject_cast<QTcpSocket*>(sender());
    buffer = readSocket->readAll();

    QString mytext = QString::fromStdString(buffer);
    qDebug() << mytext;
}

答案 2 :(得分:1)

这可以通过QSignalMapper来解决。这是(未经过完整测试的)代码:

---------------------- main.cpp ------------------

#include "rootwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    RootWindow w;
    w.show();

    return a.exec();
}

---------------------- rootwindow.h ---------------------- -

#ifndef ROOTWINDOW_H
#define ROOTWINDOW_H

#include <QMainWindow>
#include <QtDebug>
#include <QLocalServer>
#include <QLocalSocket>
#include <QSignalMapper>
#include <QList>

class RootWindow : public QMainWindow
{
    Q_OBJECT

private:

    QLocalServer *server;
    QLocalSocket *socket;

    QList<QLocalSocket*> *list;

    QSignalMapper *mapper;

public:

    RootWindow(QWidget *parent = 0);
    ~RootWindow();

private slots:

    void slotNewConnection();
    void slotReadyRead(int index);
};

#endif // ROOTWINDOW_H

------------------------ rootwindow.cpp -------------------- -----

#include "rootwindow.h"

RootWindow::RootWindow(QWidget *parent): QMainWindow(parent)
{
    server = new QLocalServer;
    list = new QList<QLocalSocket*>;

    mapper = new QSignalMapper(this);

    connect(server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
    connect(mapper, SIGNAL(mapped(int)), this, SLOT(slotReadyRead(int)));

    server->listen("TestServer");
}

RootWindow::~RootWindow()
{
    delete list;
}

void RootWindow::slotNewConnection()
{
    qWarning() << "newConnection";
    list->append(server->nextPendingConnection());

    //here you map each client to its number in the list
    mapper->setMapping(list->last(), list->length()-1);

    //here we say, that when ever a client from the QList sends readyRead() the mapper should be used
    //with the property (list->length()-1) defined in the line above
    connect(list->last(), SIGNAL(readyRead()), mapper, SLOT(map()));
}

void RootWindow::slotReadyRead(int index)
{
    qWarning() << "Client " << index << " has written: " << list->at(index)->readAll();
}

它基本上是您的代码,我只在相关行添加了QSignalMapper和一些评论。