【发布时间】:2015-10-27 05:37:28
【问题描述】:
我得到错误:
QIODevice::write (QTcpSocket): 设备未打开。 尝试后,我认为问题是将参数 server->nextPendingConnection() 传递给对象。有人可以知道如何正确地做到这一点吗?
我的理解是socketClient 的对象未正确初始化。
我正在使用带有 Qt 的 Ubuntu。
我正在使用 Qt 实现服务器。服务器部分有两个基于QTcpServer 和QTcpSocket 的类。
说Server 和SocketClient。
我正在服务器中创建 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:
};
【问题讨论】:
-
SockClient 构造函数的第二个参数 (
socket) 是否有默认参数? -
@Jan 1,不,它没有
标签: c++ qt client-server tcp-ip