QTcpServer
tcpServer = new QTcpServer(this);
connect(tcpServer, &QTcpServer::newConnection, this, &Dialog::sendData);
connect(tcpServer, &QTcpServer::acceptError, this, &Dialog::displayError);
tcpServer->listen(QHostAddress::Any, 8888);
void Dialog::sendData()
{
qDebug() << "连接成功,尝试向客户端写入数据";
QString sWriteData = "来自tcp服务端的数据";
//获取与客户端通信的socket
QTcpSocket* oneTcpSocket = tcpServer->nextPendingConnection();
//从客户端读数据
QString sReadData = oneTcpSocket->readAll();
oneTcpSocket->write(sWriteData.toUtf8());
//与客户端断开连接
// connect(oneTcpSocket, &QTcpSocket::disconnected, oneTcpSocket, &QTcpSocket::deleteLater);
// oneTcpSocket->disconnectFromHost();
}
void Dialog::displayError(QAbstractSocket::SocketError socketError)
{
qDebug() << "服务端错误消息:" << socketError;
}
QTcpSocket
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, &QTcpSocket::connected, this, &Dialog::connected);
connect(tcpSocket, &QIODevice::readyRead, this, &Dialog::readyRead);
typedef void (QAbstractSocket::*QAbstractSocketErrorSignal)(QAbstractSocket::SocketError);
connect(tcpSocket, static_cast<QAbstractSocketErrorSignal>(&QTcpSocket::error), this, &Dialog::error);
tcpSocket->connectToHost(QHostAddress::LocalHost/*"127.0.0.1"*/, 8888);
tcpSocket->waitForReadyRead();
void Dialog::readyRead()
{
qDebug() << "客户端读取信息:" << QString(tcpSocket->readAll());
}
void Dialog::connected()
{
qDebug() << "客户端连接成功";
}
void Dialog::error(QAbstractSocket::SocketError socketError)
{
qDebug() << "客户端错误信息:" << socketError;
}