【发布时间】:2017-03-16 20:23:34
【问题描述】:
我想将数据从客户端发送到服务器,当我尝试连接到 serevr 时,客户端显示未知错误,并且没有数据发送
它只显示空字符串“”,
我们将不胜感激。
代码如下:
//客户
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, SIGNAL(connected()), this, SLOT(connected()));
QHostAddress ha;
ha.setAddress("myIP");
tcpSocket->connectToHost(ha, 6401);
if(!tcpSocket->waitForConnected(3000)) {
ui->lineEdit->setText(tcpSocket->errorString());
}
else
ui->lineEdit->setText("connected");
}
void Widget::connected()
{
tcpSocket->write("hello this is client\r\n");
tcpSocket->flush();
tcpSocket->waitForBytesWritten(3000);
tcpSocket->close();
}
//服务器
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnection()));
if(!tcpServer->listen(QHostAddress::Any, 6401)) {
ui->lineEdit->setText("server not started");
}
else
ui->lineEdit->setText("server started");
}
void Widget::newConnection()
{
QTcpSocket *tcpSocket= tcpServer->nextPendingConnection();
qDebug() << tcpSocket->readAll();
tcpSocket->waitForReadyRead(3000);
tcpSocket->close();
}
【问题讨论】:
-
我认为
"myIP"只是一个占位符。如果改为指定本地环回"127.0.0.1"会发生什么? -
同样的错误发生,未知错误,空字符串。
-
读取数据时出现问题
标签: qt qtcpsocket qtcpserver