我正在创建一个简单的程序,它将“连接”到自身然后发送数据。它启动QTcpServer然后等待任何传入连接。我有一个单独的函数,它将依次尝试在localhost和我决定的端口上连接到此服务器。这在我在命令提示符下打开Telnet时有效,但现在在我的实际程序中。这是我使用的代码(有些是来自其他来源的代码段)
MainWindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
server = new QTcpServer(this);
//Initialize and start the server
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
if (!server->listen(QHostAddress::Any, 3665))
{
qDebug() << "Server failed to start!";
}
else
{
qDebug() << "Server started";
}
//Try to connect to the server
connectToServer("127.0.0.1", qint16(3665));
}
MainWindow::~MainWindow()
{
delete server;
delete ui;
}
void MainWindow::connectToServer(QString host, qint16 port)
{
qDebug() << "Connecting to " + host + " at port " + QString::number(port);
QTcpSocket socket;
socket.connectToHost(host, port);
if (!socket.waitForConnected(5000))
{
qDebug() << socket.errorString();
}
while (socket.bytesAvailable() < (int)sizeof(quint16))
{
if (!socket.waitForReadyRead(5000))
{
qDebug() << socket.errorString();
}
}
quint16 blockSize;
QDataStream in(&socket);
in.setVersion(QDataStream::Qt_5_5);
in >> blockSize;
while (socket.bytesAvailable() < blockSize)
{
if (!socket.waitForReadyRead(5000))
{
qDebug() << socket.errorString();
}
}
QString fortune;
in >> fortune;
qDebug() << fortune;
}
void MainWindow::newConnection()
{
qDebug() << "A connection has been found.";
QTcpSocket *socket = server->nextPendingConnection();
socket->write("hello client\r\n");
socket->flush();
socket->waitForBytesWritten(5000);
socket->close();
}