无法将消息从客户端发送到服务器

unable to send message from client to server

本文关键字:服务器 客户端 消息      更新时间:2023-10-16

我正在编写一个客户端-服务器程序,该服务器是多线程的,代码编译没有任何错误,但它没有显示任何来自客户端的消息。只是它运行到"qDebug()<<"客户端连接";"这是我的代码。如果你能告诉我问题出在哪里,我将不胜感激。

myclient.cpp

#include "myclient.h"
#include "QTcpsocket"
#include "QTcpServer"
#include "mainwindow.h"
#include "QHostAddress"

myclient::myclient(QObject* parent): QObject(parent)
{
}
void myclient::start(QString address, quint16 port)
  {
       QHostAddress LocalHost;
       LocalHost.setAddress(address);
        m_client.connectToHost(LocalHost, 6666);
        QObject::connect(&m_client, SIGNAL(connected()),this, SLOT(startTransfer()));
   }
void myclient::startTransfer()
{
  m_client.write("Hello", 5);
}

mythread.cpp

#include "mythread.h"
#include "myserver.h"
mythread::mythread(QTcpSocket*, QObject *parent) :
QThread(parent)
{
}
void mythread::run()
{
  qDebug() << " Thread started";
    if (m_client)
  {
  connect(m_client, SIGNAL(connected()), this, SLOT(readyRead()), Qt::DirectConnection);
  }

 qDebug() << " Client connected";
     exec();
  }

void mythread::readyRead()
{
  QByteArray Data = m_client->readAll();
  qDebug()<< " Data in: " << Data;
  m_client->write(Data);
}

void mythread::disconnected()
{
  qDebug() << " Disconnected";
  m_client->deleteLater();
  exit(0);
}

myserver.cpp

#include "myserver.h"
#include "mythread.h"

myserver::myserver(QObject *parent) :
QObject(parent)
{
}
void myserver::startserver()
{
  connect(&m_server,SIGNAL(newConnection()), this ,SLOT(newConnection()));
  int port = 6666;
  if(m_server.listen(QHostAddress::Any, port))
  {        
    qDebug() << "Listening to port " ;
  }
 else
  {
    qDebug() << "Could not start server "<<m_server.errorString();
  }
  }

void myserver::newConnection()
{
 m_client = m_server.nextPendingConnection();
 qDebug() << " Connecting...";
 mythread *thread = new mythread(m_client,this);
 thread->start();
}
关于nextPendingConnection()的文档说明:

注意:返回的QTcpSocket对象不能从其他对象使用线如果您想使用来自另一个线程的传入连接,您需要重写incomingConnection()。

所以,你不能在另一个线程中使用那个套接字。正如文档所说,您可以子类化QTcpServer并覆盖incomingConnection(),每当客户端尝试连接到服务器时,就会调用此方法。

incomingConnection()方法提供了一个套接字描述符(就像常规文件描述符一样)。然后,您可以将套接字描述符传递给另一个线程,并在那里完全创建QTcpSocket

在这个线程中,你需要这样的东西:

QTcpSocket client = new QTcpSocket();
client.setSocketDescriptor(sockId);
// Now, you can use this socket as a connected socket.
// Make sure to connect its ready read signal to your local slot.

进入newConnection后,客户端已经连接,您只需要启动一个调用readAll然后回复的线程。

不需要再次等待connected()信号

编辑

QSocket类被设计为基于事件在主线程上异步工作。来自文件:

警告:QSocket不适合在线程中使用。如果需要在线程中使用套接字,请使用较低级别的QSocketDevice类。