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

标签 c++ qt client-server tcp

我得到错误:

QIODevice::write (QTcpSocket): device not open. After trying , I think problem is passing parameter server->nextPendingConnection() into object. Can someone has idea how to do it correctly?

我的理解是 socketClient 的对象未正确初始化。 我正在使用带有 Qt 的 Ubuntu。

我正在使用 Qt 实现服务器。服务器部分有两个基于QTcpServerQTcpSocket 的类。 说 ServerSocketClient。 我正在服务器中创建 SocketClient 对象,出于测试目的,我打开了 telnet session 并希望看到该服务器在终端上写“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:
};

最佳答案

您使用:

socketClient = new QTcpSocket( socket );

尝试改用下面的代码:

socketClient = socket;

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

代替

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

关于c++ - 设备未打开错误 + QIODevice::write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31815655/

相关文章:

python - 绘画程序框架

linux - 使用FTP向设备传输文件,是否需要运行服务器?

c++ - 使用 OpenSSL 1.1.1d 静态编译 Qt 5.13.1 生成 QSslSocket::connectToHostEncrypted: TLS 初始化失败

java - 在 Java 中,不可序列化的套接字是否必须阻止使用客户端-服务器观察者模式?

python - 两个客户端无法在套接字客户端-服务器连接中相互通信

c++ - boost 变体 : how to get currently held type?

c++ - 在 Bazel 中更新单个外部存储库

perl - 如何为Net::WebSocket::Server程序编写客户端程序?

c++ - 如何在数组或链表中查找特定字符串

c++ - 检查整个数组是否为空