默认情况下,QTcpSocket是异步的,因此当您调用connectToHost并在相同的上下文中写入时,将不会发送,因为套接字未连接.你应该改变你的“客户端”代码:
void TopLevelComms::connect(){
tcpSocket->connectToHost(hostAddress,QIODevice::ReadWrite);
if(tcpSocket->waitForConnected()) // putting 1 as parameter isn't reasonable,using default 3000ms value
{
QString string = "Hello";
QByteArray array;
array.append(string);
qDebug()<write(array);
}
else
{
qDebug() << "couldn't connect";
}
}
注意:您也没有检查是否能够听
void Comms::attemptConnection(){
connect(server,SLOT(connectionAccepted()));
//socket = server->nextPendingConnection();
if(server->listen(hostAddress,hostPort))
{
qDebug() << "Server listening";
}
else
{
qDebug() << "Couldn't listen to port" << server->serverPort() << ":" << server->errorString();
}
//receivedData = socket->readAll();
}
最后一件事.请注意,QTcpServer :: nextPendingConnection()返回QTcpSocket,因此,不要采用新的连接,您可以使用nextPendingConnection创建新的QTcpSocket作为父
void Comms::connectionAccepted(){
qDebug()<
// WRONG! it will use QTcpSocket::QTcpSocket(QObject * parent)
//socket = new QTcpSocket(server->nextPendingConnection());
// use simple asign
socket = server->nextPendingConnection();
// move reading to slot
connect(socket,SIGNAL(readyRead()),SLOT(readSocket()));
}
现在我们将把阅读移到单独的插槽
void Comms::readSocket()
{
// note that dynamic size array is incompatible with some compilers
// we will use Qt data structure for that
//char* rec = new char[socket->readBufferSize()];
qDebug()<readBufferSize();
// note that QByteArray can be casted to char * and const char *
QByteArray data = socket->readAll();
}
我必须承认,这样的小代码示例是很多错误.您需要了解有关TCP / IP连接的一些知识.那些是流,并且没有一个保证,整个数据块将一次给你