qt的tcp,ip代码编写
时间: 2023-08-06 15:12:40 浏览: 47
以下是一个简单的使用 Qt 的 TCP/IP 代码示例,用于建立客户端和服务器间的连接:
### 服务器端代码
```cpp
#include <QTcpServer>
#include <QTcpSocket>
void Server::startServer()
{
tcpServer = new QTcpServer(this);
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnection()));
if (!tcpServer->listen(QHostAddress::Any, 8888))
{
qDebug() << "Error: " << tcpServer->errorString();
}
else
{
qDebug() << "Server started!";
}
}
void Server::newConnection()
{
QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readClient()));
connect(clientSocket, SIGNAL(disconnected()), clientSocket, SLOT(deleteLater()));
qDebug() << "New client connected!";
}
void Server::readClient()
{
QTcpSocket *clientSocket = (QTcpSocket*)sender();
QByteArray data = clientSocket->readAll();
qDebug() << "Received data: " << data;
}
```
### 客户端代码
```cpp
#include <QTcpSocket>
void Client::startClient()
{
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, SIGNAL(connected()), this, SLOT(connected()));
connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
tcpSocket->connectToHost("localhost", 8888);
}
void Client::connected()
{
qDebug() << "Connected to server!";
}
void Client::disconnected()
{
qDebug() << "Disconnected from server!";
}
void Client::readyRead()
{
QByteArray data = tcpSocket->readAll();
qDebug() << "Received data: " << data;
}
void Client::displayError(QAbstractSocket::SocketError socketError)
{
qDebug() << "Error: " << tcpSocket->errorString();
}
```
请注意,这只是一个简单的示例,您需要根据您的实际需求进行更改和调整。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)