用qt写一个 tcp服务器修改客户端的port的示例程序
时间: 2023-06-04 21:03:54 浏览: 112
Qt编写的TCP客户端
好的,以下是示例代码:
```cpp
#include <QTcpServer>
#include <QTcpSocket>
// 自定义信号槽,用于客户端连接成功时处理
class Server : public QTcpServer {
Q_OBJECT
public:
explicit Server(QObject* parent = nullptr) : QTcpServer(parent) {}
signals:
void clientConnected(QTcpSocket*);
protected:
void incomingConnection(qintptr socketDescriptor) override {
QTcpSocket* clientSocket = new QTcpSocket(this);
clientSocket->setSocketDescriptor(socketDescriptor);
emit clientConnected(clientSocket);
}
};
// 客户端
class Client : public QObject {
Q_OBJECT
public:
explicit Client(QObject* parent = nullptr) : QObject(parent) {}
void connectToServer(const QString& hostName, quint16 port) {
m_socket.connectToHost(hostName, port);
}
bool isConnected() const {
return m_socket.state() == QAbstractSocket::ConnectedState;
}
void changePort(quint16 port) {
m_socket.write(QString::number(port).toUtf8());
m_socket.flush();
}
private:
QTcpSocket m_socket;
};
#include <QCoreApplication>
int main(int argc, char* argv[]) {
QCoreApplication a(argc, argv);
Server server;
Client client;
// 当有客户端连接时,处理如下逻辑
QObject::connect(&server, &Server::clientConnected, &client, [&](QTcpSocket* clientSocket) {
// 连接成功,修改端口为8888
client.connectToServer("localhost", 8888);
while (!client.isConnected()) {
// 等待连接成功
qApp->processEvents();
}
client.changePort(9999);
// 操作完成,断开连接
clientSocket->close();
delete clientSocket;
});
// 启动服务器,监听端口8888
server.listen(QHostAddress::Any, 8888);
return a.exec();
}
```
注意:以上示例仅供演示/学习用途,实际开发中需考虑更多因素,如错误处理、协议设计等。
阅读全文