QTcpSocket和QTcpServer通讯的代码
时间: 2023-05-18 07:03:29 浏览: 102
可以参考以下代码:
QTcpServer *server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
if(!server->listen(QHostAddress::Any, 1234)){
qDebug() << "Server could not start!";
}else{
qDebug() << "Server started!";
}
void MyClass::newConnection(){
QTcpSocket *socket = server->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
qDebug() << "New client connected!";
}
void MyClass::readyRead(){
QTcpSocket *socket = static_cast<QTcpSocket*>(sender());
qDebug() << "Data received: " << socket->readAll();
}
void MyClass::disconnected(){
QTcpSocket *socket = static_cast<QTcpSocket*>(sender());
socket->deleteLater();
qDebug() << "Client disconnected!";
}
阅读全文