Qt tcp/ip通讯
在.pro 文件中添加 QT += network
1、简单 无窗口例子
服务端
#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTcpServer server;
server.listen(QHostAddress::Any, 12345); // 监听所有网络接口上的1234端口
QObject::connect(&server, &QTcpServer::newConnection, [&]() {
QTcpSocket *socket = server.nextPendingConnection();
qDebug() << "New client connected!";
socket->write("Hello client!"); // 向客户端发送数据
socket->waitForBytesWritten();
socket->waitForReadyRead();
qDebug() << "Received data from client:" << socket->readAll(); // 读取客户端发送的数据
socket->close(); // 关闭连接
});
return a.exec();
}
客户端
#include <QCoreApplication>
#include <QTcpSocket>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 12345); // 连接到服务器的IP地址和端口号
if (socket.waitForConnected()) {
cout << "Connected to server!"<< endl;
socket.write("Hello server!"); // 向服务器发送数据
socket.waitForBytesWritten();
socket.waitForReadyRead();
cout << "Response from server:" << socket.readAll().toStdString() << endl; // 读取服务器的响应数据
socket.close(); // 关闭连接
} else {
cout << "Failed to connect to server."<<endl;;
}
return a.exec();
}