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

C++ 无法将消息从客户端发送到服务器,c++,qt,C++,Qt,我正在编写一个客户机-服务器程序,服务器是多线程的,代码编译没有任何错误,但它没有显示来自客户机的任何消息。 只要在进入newConnection后运行到“qDebug(),客户端就已经连接好了,您只需要启动一个线程,调用readAll,然后回复 无需再次等待connected()信号 编辑 QSocket类被设计为基于事件在主线程上异步工作 警告:QSocket不适合在线程中使用。如果需要在线程中使用套接字,请使用较低级别的QSocketDevice类 关于nextPendingConnect

我正在编写一个客户机-服务器程序,服务器是多线程的,代码编译没有任何错误,但它没有显示来自客户机的任何消息。 只要在进入
newConnection
后运行到“qDebug(),客户端就已经连接好了,您只需要启动一个线程,调用
readAll
,然后回复

无需再次等待
connected()
信号

编辑
QSocket
类被设计为基于事件在主线程上异步工作

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

关于
nextPendingConnection()
说:

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

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

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

在该线程中,您需要以下内容:

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.

请回答您的问题并添加服务器的代码。我忽略已连接的()但它仍然不起作用!我在运行服务器时遇到以下错误:程序意外完成。哦,你是对的,我们不能在后台线程中使用该套接字。它会引发异常。@Hanita:抱歉。我的回答基于一般套接字编程技术。
QSocket
是一个具有完全dif的高级对象不同的方法…您应该参考文档以获得示例客户机/服务器解决方案(例如)
#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);
}
#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();

}
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.