Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. I wanna develope chatprogram...

I wanna develope chatprogram...

Scheduled Pinned Locked Moved Unsolved General and Desktop
2 Posts 2 Posters 228 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H Offline
    H Offline
    hailee
    wrote on last edited by
    #1

    In chatmain.ui, there is a button to connect to the server by entering the IP and port number. When this button is clicked, a new client is created and the chatwindow.ui window is created where users can enter their username and chat with other clients. This window displays a list of connected users, a chat window, a text input field, and a send button. Clients can exchange messages in the chat window. I wrote the code for this chat program using QT C++ and QTcpSocket, but it doesn't run. Can you tell me what the problem is?

    chatmain.h

    #ifndef CHATMAIN_H
    #define CHATMAIN_H
    
    #include <QMainWindow>
    #include <QWidget>
    #include <QTcpSocket>
    #include <QTcpServer>
    #include <QMessageBox>
    #include "chatwindow.h"
    
    QT_BEGIN_NAMESPACE
    namespace Ui {
    class ChatMain;
    }
    QT_END_NAMESPACE
    
    class ChatMain : public QMainWindow
    {
        Q_OBJECT
    
    public:
        ChatMain(QWidget *parent = nullptr);
        ~ChatMain();
    
    private slots:
        void connectToServer();
        void newConnectionSlot(QTcpSocket *socket, QWidget *parent);
        void broadcastMessage(const QString &message);
        void clientDisconnected(QTcpSocket* socket);
    
    private:
        Ui::ChatMain *ui;
        ChatWindow* chatwindow;
        QTcpServer* server;
        QTcpSocket* socket;
        QList<ChatWindow*> clients;
        int cnt = 0;
    };
    #endif // CHATMAIN_H
    
    

    chatmain.cpp

    #include "chatmain.h"
    #include "ui_chatmain.h"
    #include "chatwindow.h"
    
    ChatMain::ChatMain(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::ChatMain)
    {
        QMainWindow mainWindow;
        ui->setupUi(this);
        setWindowTitle("Chatting Client");
        ui->ipLineEdit->setText("192.168.219.104");
    
        server = new QTcpServer(this);
        connect(ui->connectBtn, SIGNAL(clicked()), this, SLOT(connectToServer()));
    
    }
    
    ChatMain::~ChatMain()
    {
        delete ui;
        delete socket;
    }
    
    
    void ChatMain::connectToServer()
    {
        cnt++; // connect횟수
        QString host = ui->ipLineEdit->text(); // 서버주소
        bool ok;
        qint16 port = ui->portLineEdit->text().toInt(&ok);// 포트번호
        QString ports = QString::number(port);
        if (host.isEmpty()) {
            QMessageBox::critical(nullptr, "Error", "서버 주소를 입력하세요.");
            return;
        }
        if(!ok) {
            QMessageBox::critical(nullptr, "Error", "유효한 포트 번호를 입력하세요.");
            return;
        }
    
        if(server->listen(QHostAddress(host), port)) {
            ui->connectBtn->setText("연결 끊기");
    
        } else {
            ui->connect_state->append("Connection failed!");
            return;
        }
    
    
        ui->connect_state->append("Connected to server!");
    
        chatwindow = new ChatWindow(socket, this);
        chatwindow->show();
    
        connect(server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot(socket, this)));
    
    }
    
    void ChatMain::newConnectionSlot(QTcpSocket *socket, QWidget *parent) {
    
    
        chatwindow = new ChatWindow(socket, parent);
        chatwindow->show();
    
    
        ChatWindow *client = new ChatWindow(socket, this);
    
        clients.append(client);
    
        connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected(socket)));
    
    
        client -> sendMessage("USERNAME");
    
        // 클라이언트에게 사용자 이름 설정 요청 메세지 전송
        connect(client, SIGNAL(messageReceived(QString)), this, SLOT(broadcastMessage("USERNAME")));
    
    }
    
    void ChatMain::broadcastMessage(const QString &message) {
        for (ChatWindow *client : clients) {
            client->sendMessage(message);
        }
    }
    
    void ChatMain::clientDisconnected(QTcpSocket* socket) {
        // 연결 종료 시 처리 내용 작성
        clients.removeOne((void*)socket);
        socket->deleteLater();
    }
    
    

    chatwindow.h

    #ifndef CHATWINDOW_H
    #define CHATWINDOW_H
    
    #include <QMainWindow>
    #include <QObject>
    #include <QTcpSocket>
    
    namespace Ui {
    class ChatWindow;
    }
    
    class ChatWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit ChatWindow(QTcpSocket *socket, QWidget *parent = 0);
        ~ChatWindow();
    
    signals:
        void disconnected();
        void messageReceived(QString);
    
    private:
        Ui::ChatWindow *ui;
        QTcpSocket *socket;
        QString username;
    
    public slots:
        void readMessage();
        void sendMessage(const QString &message);
        void setUserName();
    
    };
    
    
    #endif // CHATWINDOW_H
    
    

    chatwindow.cpp

    #include "chatwindow.h"
    #include "ui_chatwindow.h"
    
    ChatWindow::ChatWindow(QTcpSocket *socket, QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::ChatWindow)
        , socket(socket)
    {
        ui->setupUi(this);
        connect(ui->setUserName, SIGNAL(clicked()), this, SLOT(setUserName()));
        connect(parent, SIGNAL(&QTcpSocket::readyRead), this, SLOT(readMessage()));
        connect(parent, SIGNAL(&QTcpSocket::disconnected), this, SLOT(disconnected()));
    }
    
    
    ChatWindow::~ChatWindow()
    {
        delete ui;
    }
    
    void ChatWindow::setUserName() {
        username = ui->userName->text();
    
    }
    
    
    void ChatWindow::readMessage() {
        QByteArray data = socket->readAll();
        QString message(data);
    
        // 메시지 처리 (예: 사용자 이름 설정, 채팅 메시지 전송 등)
        if (message.startsWith("USERNAME")) {
            // 사용자 이름 설정
            username = ui->userName->text();
            emit messageReceived("[" + username + "] 접속했습니다.");
            ui->connectedUsers->setText("[" + username + "] 접속했습니다.");
        } else {
            // 채팅 메시지 전송
            emit messageReceived("[" + username + "]: " + message);
        }
    }
    
    void ChatWindow::sendMessage(const QString &message) {
        socket->write(message.toUtf8());
    }
    
    
    
    

    chatmain.ui
    KakaoTalk_20240423_171041132.png

    chatwindow.ui
    KakaoTalk_20240423_171048756.png

    JonBJ 1 Reply Last reply
    0
    • H hailee

      In chatmain.ui, there is a button to connect to the server by entering the IP and port number. When this button is clicked, a new client is created and the chatwindow.ui window is created where users can enter their username and chat with other clients. This window displays a list of connected users, a chat window, a text input field, and a send button. Clients can exchange messages in the chat window. I wrote the code for this chat program using QT C++ and QTcpSocket, but it doesn't run. Can you tell me what the problem is?

      chatmain.h

      #ifndef CHATMAIN_H
      #define CHATMAIN_H
      
      #include <QMainWindow>
      #include <QWidget>
      #include <QTcpSocket>
      #include <QTcpServer>
      #include <QMessageBox>
      #include "chatwindow.h"
      
      QT_BEGIN_NAMESPACE
      namespace Ui {
      class ChatMain;
      }
      QT_END_NAMESPACE
      
      class ChatMain : public QMainWindow
      {
          Q_OBJECT
      
      public:
          ChatMain(QWidget *parent = nullptr);
          ~ChatMain();
      
      private slots:
          void connectToServer();
          void newConnectionSlot(QTcpSocket *socket, QWidget *parent);
          void broadcastMessage(const QString &message);
          void clientDisconnected(QTcpSocket* socket);
      
      private:
          Ui::ChatMain *ui;
          ChatWindow* chatwindow;
          QTcpServer* server;
          QTcpSocket* socket;
          QList<ChatWindow*> clients;
          int cnt = 0;
      };
      #endif // CHATMAIN_H
      
      

      chatmain.cpp

      #include "chatmain.h"
      #include "ui_chatmain.h"
      #include "chatwindow.h"
      
      ChatMain::ChatMain(QWidget *parent)
          : QMainWindow(parent)
          , ui(new Ui::ChatMain)
      {
          QMainWindow mainWindow;
          ui->setupUi(this);
          setWindowTitle("Chatting Client");
          ui->ipLineEdit->setText("192.168.219.104");
      
          server = new QTcpServer(this);
          connect(ui->connectBtn, SIGNAL(clicked()), this, SLOT(connectToServer()));
      
      }
      
      ChatMain::~ChatMain()
      {
          delete ui;
          delete socket;
      }
      
      
      void ChatMain::connectToServer()
      {
          cnt++; // connect횟수
          QString host = ui->ipLineEdit->text(); // 서버주소
          bool ok;
          qint16 port = ui->portLineEdit->text().toInt(&ok);// 포트번호
          QString ports = QString::number(port);
          if (host.isEmpty()) {
              QMessageBox::critical(nullptr, "Error", "서버 주소를 입력하세요.");
              return;
          }
          if(!ok) {
              QMessageBox::critical(nullptr, "Error", "유효한 포트 번호를 입력하세요.");
              return;
          }
      
          if(server->listen(QHostAddress(host), port)) {
              ui->connectBtn->setText("연결 끊기");
      
          } else {
              ui->connect_state->append("Connection failed!");
              return;
          }
      
      
          ui->connect_state->append("Connected to server!");
      
          chatwindow = new ChatWindow(socket, this);
          chatwindow->show();
      
          connect(server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot(socket, this)));
      
      }
      
      void ChatMain::newConnectionSlot(QTcpSocket *socket, QWidget *parent) {
      
      
          chatwindow = new ChatWindow(socket, parent);
          chatwindow->show();
      
      
          ChatWindow *client = new ChatWindow(socket, this);
      
          clients.append(client);
      
          connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected(socket)));
      
      
          client -> sendMessage("USERNAME");
      
          // 클라이언트에게 사용자 이름 설정 요청 메세지 전송
          connect(client, SIGNAL(messageReceived(QString)), this, SLOT(broadcastMessage("USERNAME")));
      
      }
      
      void ChatMain::broadcastMessage(const QString &message) {
          for (ChatWindow *client : clients) {
              client->sendMessage(message);
          }
      }
      
      void ChatMain::clientDisconnected(QTcpSocket* socket) {
          // 연결 종료 시 처리 내용 작성
          clients.removeOne((void*)socket);
          socket->deleteLater();
      }
      
      

      chatwindow.h

      #ifndef CHATWINDOW_H
      #define CHATWINDOW_H
      
      #include <QMainWindow>
      #include <QObject>
      #include <QTcpSocket>
      
      namespace Ui {
      class ChatWindow;
      }
      
      class ChatWindow : public QMainWindow
      {
          Q_OBJECT
      
      public:
          explicit ChatWindow(QTcpSocket *socket, QWidget *parent = 0);
          ~ChatWindow();
      
      signals:
          void disconnected();
          void messageReceived(QString);
      
      private:
          Ui::ChatWindow *ui;
          QTcpSocket *socket;
          QString username;
      
      public slots:
          void readMessage();
          void sendMessage(const QString &message);
          void setUserName();
      
      };
      
      
      #endif // CHATWINDOW_H
      
      

      chatwindow.cpp

      #include "chatwindow.h"
      #include "ui_chatwindow.h"
      
      ChatWindow::ChatWindow(QTcpSocket *socket, QWidget *parent)
          : QMainWindow(parent)
          , ui(new Ui::ChatWindow)
          , socket(socket)
      {
          ui->setupUi(this);
          connect(ui->setUserName, SIGNAL(clicked()), this, SLOT(setUserName()));
          connect(parent, SIGNAL(&QTcpSocket::readyRead), this, SLOT(readMessage()));
          connect(parent, SIGNAL(&QTcpSocket::disconnected), this, SLOT(disconnected()));
      }
      
      
      ChatWindow::~ChatWindow()
      {
          delete ui;
      }
      
      void ChatWindow::setUserName() {
          username = ui->userName->text();
      
      }
      
      
      void ChatWindow::readMessage() {
          QByteArray data = socket->readAll();
          QString message(data);
      
          // 메시지 처리 (예: 사용자 이름 설정, 채팅 메시지 전송 등)
          if (message.startsWith("USERNAME")) {
              // 사용자 이름 설정
              username = ui->userName->text();
              emit messageReceived("[" + username + "] 접속했습니다.");
              ui->connectedUsers->setText("[" + username + "] 접속했습니다.");
          } else {
              // 채팅 메시지 전송
              emit messageReceived("[" + username + "]: " + message);
          }
      }
      
      void ChatWindow::sendMessage(const QString &message) {
          socket->write(message.toUtf8());
      }
      
      
      
      

      chatmain.ui
      KakaoTalk_20240423_171041132.png

      chatwindow.ui
      KakaoTalk_20240423_171048756.png

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by
      #2

      @hailee said in I wanna develope chatprogram...:

      but it doesn't run. Can you tell me what the problem is?

      Depends what "doesn't run" means....

      connect(parent, SIGNAL(&QTcpSocket::readyRead), this, SLOT(readMessage()));

      Here at least you mix old style and new style signal/slot connect() syntax. Don't, and change over to only using new style, it has been recommended for over a decade.

      How does parent, which is a QWidget *, have any QTcpSocket signals?

      1 Reply Last reply
      3

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved