在服务器和客户端的.pro文件中
均添加:
QT += network
客户端需添加头文件
#include <QTcpSocket>
#include <QHostAddress>
#include <QMessageBox>
服务器需添加头文件:
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
server.cpp
#include "server.h"
#include "ui_server.h"
Server::Server(QWidget *parent) :
QWidget(parent),
ui(new Ui::Server)
{
ui->setupUi(this);
this->setWindowTitle("服务器");
server = new QTcpServer;
server->listen(QHostAddress::AnyIPv4,8888);//监听8888端口
//系统发送newConnection信号,服务器接收信号并连接
connect(server,&QTcpServer::newConnection,this,&Server::connection);
}
Server::~Server()
{
delete ui;
}
void Server::connection()
{
QTcpSocket *socket = server->nextPendingConnection();//创建socket连接
QHostAddress clientAddress = socket->peerAddress();
quint16 clientPort = socket->peerPort();
ui->addresslineEdit->setText(clientAddress.toString());
ui->portlineEdit->setText(QString::number(clientPort));
//系统发送readyRead信号,服务器接受信号处理数据
connect(socket,&QTcpSocket::readyRead,this,&Server::DataDealing);
}
void Server::DataDealing()处理readyRead信号读取数据
{
QTcpSocket *socket = (QTcpSocket *)sender();//获取信号发送者
ui->textEdit->setText(QString(socket->readAll()));//显示信息
}
Server.h
#ifndef SERVER_H
#define SERVER_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void connection();
void DataDealing();
private:
Ui::Server*ui;
QTcpServer *server;
};
#endif // SERVER_H
Client
构造函数:
this->setWindowTitle("客户端");
client = new QTcpSocket;//实例化socket通信对象
connect(client,&QTcpSocket::connected,
[=]
{
QMessageBox::information(this,"连接提示","连接成功");
this->close();
chat *c = new chat(client);
c->show();
}
);
获取IP地址及端口以连接/登录服务器:
QHostAddress serverAddress(ui->le_addr->text());
qint16 serverPort = ui->le_port->text().toShort();
client->connectToHost(serverAddress,serverPort);
登出直接this->close();
关闭窗口即可