pro添加模块与includ头文件
QT += network
#include <QList>
#include <QTcpSocket>
#include <QTcpServer>
#include <QNetworkInterface>
client端
socket = new QTcpSocket;
socket -> connectToHost(serverIP, 8888);
connect(socket, SIGNAL(connected()), this, SLOT(connectedSlot()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorSlot(QAbstractSocket::SocketError)));
socket -> write(data);
qDebug() << socket -> errorString();
qDebug() << socketError;
server端
server = new QTcpServer;
connect(server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
bool ok = server -> listen(QHostAddress::Any, 8888);
qDebug() << "listen: " << ok;
void SyncFileServer::newConnectionSlot()
{
QTcpSocket* socket = server -> nextPendingConnection();
socketList.append(socket);
qDebug() << "new connectd: " << socket;
connect(socket, SIGNAL(connected()), this, SLOT(connectedSlot()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorSlot(QAbstractSocket::SocketError)));
}
QTcpSocket* s = qobject_cast<QTcpSocket*>(this -> sender());
while (!s -> atEnd())
{
QByteArray lineData = s -> readLine();
// ...
}
QTcpSocket* s = qobject_cast<QTcpSocket*>(this -> sender());
socketList.removeAll(s);
socketList.clear();