设备未打开错误+ QIODevice :: write

时间:2015-08-04 17:29:09

标签: c++ qt client-server tcp-ip

我收到错误:

  

QIODevice :: write(QTcpSocket):设备未打开。   尝试后,我认为问题是将参数server-> nextPendingConnection()传递给对象。有人可以知道如何正确地做到这一点吗?

我的理解是socketClient的对象未正确初始化。 我正在使用Utntu和Qt。

我正在使用Qt实现服务器。服务器部分有两个基于QTcpServerQTcpSocket的类。 说ServerSocketClient。 我在服务器中创建SocketClient的对象并且为了测试目的我打开了telnet会话并希望看到该服务器在终端上写“hello”。但不知何故它不起作用。有人可以告诉我我犯错的地方。

Server::Server(QObject *parent) : QObject(parent)
{
  server_obj = new QTcpServer( this ); 
}

void Server::startServer()
{
  connect( server_obj, SIGNAL( newConnection() ), this, SLOT( incomingConnection() ) );
  if( !server_obj->listen( QHostAddress::Any, 9999) )
  {
    qDebug() << " Server failed to get started";
  }
  else
  {
   qDebug() << " Server started"; // this is successful
  }
}


void Server::incomingConnection()
{
  socketforClient = new SockClient( server_obj->nextPendingConnection() );// has a doubt on nextPendingconection??

  //only for testing remove it
  socketforClient->writeToClient();
}

客户类

 * Description: Its a constructor.I have changed default constructor to add QTcpSocket* object in parameter.I used this constructor in  void Server::incomingConnection()
 */
SockClient::SockClient(QObject *parent,QTcpSocket* socket ) : QObject(parent)
{
  socketClient = new QTcpSocket( socket );

 qDebug() << " we are in constructor of 1st sockclient ";

}



// this is for testing purpose only

void SockClient::writeToClient()
{
   socketClient->write(" hello world\r\n");
   socketClient->flush();
   socketClient->waitForBytesWritten(3000);

}

// SockClient的头文件

class SockClient : public QObject
{
  Q_OBJECT
public:

 explicit  SockClient( QObject *parent, QTcpSocket* socket= 0 ); // I have created
    void writeToClient(); // This is for testing purpose
 ~SockClient();
signals:

private slots:
  void readClient();

private:
  void sendResponsetoMops();

  QTcpSocket *socketClient;

  quint16 nextBlockSize;

public slots:
};

1 个答案:

答案 0 :(得分:0)

您使用:

socketClient = new QTcpSocket( socket );

尝试使用以下代码:

socketClient = socket;

并使用  socketforClient = new SockClient(this, server->nextPendingConnection() );

而不是

 socketforClient = new SockClient( server->nextPendingConnection() );