首先使用TCP通信需要在.pro文件中加入:QT += network
服务器.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include
#include
#include
#include
#include
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = NULL);
~Widget();
void updateList();
private slots:
void on_pushButton_send_2_clicked();
void on_pushButton_set_clicked();
void dealnewConnection();
void dealreadyRead();
void dealdisconnected();
void dealclicked(QModelIndex);
void on_pushButton_clicked();
private:
Ui::Widget *ui;
QTcpServer *m_Server;
QTcpSocket *m_Socket;
QList<QTcpSocket*> m_list;
QTcpSocket *m_SocketNow = NULL;
QStringList m_listStr;
int m_cnt;
};
#endif // WIDGET_H
服务器.cpp文件
#include "widget.h"
#include "ui_widget.h"
#include
#include
#include
#include
#include
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
/*设置不可编辑*/
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
/*获取本机ip*/
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
/*use the first non-localhost IPv4 address*/
QString ipAddress;
for (int i = 0; i < ipAddressesList.size(); ++i) {
qDebug()<<ipAddressesList.at(i);
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
ui->label_seriviceIp->setText("本级ip:"+ipAddress);
}
void Widget::on_pushButton_set_clicked()
{
/*初始化服务器server对象*/
m_Server = new QTcpServer();
/*启动服务器监听*/
m_Server->listen(QHostAddress::Any,ui->lineEdit_Setport->text().toInt());
/*关联客户端连接信号newConnection*/
connect(m_Server,SIGNAL(newConnection()),this,SLOT(dealnewConnection()));
ui->pushButton_set->setEnabled(false);
}
void Widget::dealnewConnection()
{
/*与客户端通信的套接字*/
m_Socket = m_Server->nextPendingConnection();
/*获取客户端ip*/
QString ip = m_Socket->peerAddress().toString();
/*关联接收客户端数据信号readyRead信号(客户端有数据就会发readyRead信号)*/
connect(m_Socket,SIGNAL(readyRead()),this,SLOT(dealreadyRead()));
/*检测掉线信号*/
connect(m_Socket,SIGNAL(disconnected()),this,SLOT(dealdisconnected()));
/*同一ip打开了两次,以区分*/
m_listStr.append(QString("%1").arg(m_cnt) + "#" + ip );
m_cnt ++;
m_list.append(m_Socket);
updateList();
ui->textBrowser->append("客户端" + ip + "连接!" );
}
void Widget::dealreadyRead()
{
/*可以实现同时读取多个客户端发送过来的消息*/
QTcpSocket *obj = (QTcpSocket*)sender();
/*获取ip*/
QString ip = obj->peerAddress().toString();
/*读取消息*/
QString msg = obj->readAll();
/*获取当前时间*/
QDateTime current_date_time =QDateTime::currentDateTime();
QString current_date =current_date_time.toString("hh:mm:ss");
ui->textBrowser->append(QString("客户端%1\t %2").arg(ip).arg(current_date));
ui->textBrowser->append(QString("%1").arg(msg));
}
void Widget::on_pushButton_send_2_clicked()
{
if(!m_SocketNow)
{
ui->label->setText("没有选择客户端!");
return;
}
else if(ui->lineEdit_information_2->text() == "")
{
ui->label->setText("发送内容为空!");
return;
}
/*取发送信息编辑框内容*/
QString msg = ui->lineEdit_information_2->text();
/*转编码*/
m_SocketNow->write(msg.toUtf8());
QString ip = m_SocketNow->peerAddress().toString();
QDateTime current_date_time =QDateTime::currentDateTime();
QString current_date =current_date_time.toString("hh:mm:ss");
ui->textBrowser->append(QString("发送消息到%1\t %2").arg(ip).arg(current_date));
ui->textBrowser->append(msg);
}
void Widget::dealdisconnected()
{
QTcpSocket *obj = (QTcpSocket*)sender();//掉线对象
QString ip = obj->peerAddress().toString();//打印出掉线对象的ip
ui->textBrowser->append("客户端" + ip + "断开连接!" );
for(int i=0; i<m_list.length(); i++)
{
if(obj == m_list.at(i))
{
m_listStr.removeAt(i);
m_list.removeAt(i);
}
}
updateList();
}
Widget::~Widget()
{
delete ui;
}
void Widget::updateList()
{
ui->label_status_3->setText(QString("当前连接数:%1").arg(m_listStr.length()));
if(m_listStr.length() == 0)
{
m_SocketNow = NULL;
ui->label->clear();
}
QStringListModel *Model = new QStringListModel(m_listStr);
ui->listView->setModel(Model);
ui->listView->setModel(Model);
connect(ui->listView,SIGNAL(clicked(QModelIndex)),this,SLOT(dealclicked(QModelIndex)));
}
void Widget::dealclicked(QModelIndex index)
{
QString str = index.data().toString();
ui->label->setText("接收客户端ip:" + str);
for( int i=0; i<m_listStr.length(); i++)
{
if(m_listStr.at(i) == str)
m_SocketNow = m_list.at(i);
}
}
void Widget::on_pushButton_clicked()
{
if(!m_SocketNow)
return;
m_SocketNow->disconnectFromHost();
for(int i=0; i<m_list.length(); i++)
{
if(m_SocketNow == m_list.at(i))
{
m_listStr.removeAt(i);
m_list.removeAt(i);
}
}
updateList();
}
客户端.h文件
#ifndef CLIENT_H
#define CLIENT_H
#include
#include
#include
namespace Ui {
class client;
}
class client : public QWidget
{
Q_OBJECT
public:
explicit client(QWidget *parent = NULL);
~client();
private slots:
void on_pushButton_connect_clicked();
void on_pushButton_disconnect_clicked();
void on_pushButton_send_clicked();
void dealreadyRead();
void dealconnected();
void dealdisconnected();
private:
Ui::client *ui;
QTcpServer *m_Server;
QTcpSocket *m_Socket = NULL;
};
#endif // CLIENT_H
客户端.cpp文件
#include "client.h"
#include "ui_client.h"
#include
client::client(QWidget *parent) :
QWidget(parent),
ui(new Ui::client)
{
ui->setupUi(this);
}
client::~client()
{
delete ui;
}
void client::on_pushButton_connect_clicked()
{
/*初始化套接字对象*/
m_Socket = new QTcpSocket(this);
/*检测链接成功信号关联槽函数*/
connect(m_Socket,SIGNAL(connected()),this,SLOT(dealconnected()));
/*连接服务器,设置ip和端口号*/
m_Socket->connectToHost(ui->lineEdit_ip->text(),ui->lineEdit_port->text().toInt());
}
void client::on_pushButton_disconnect_clicked()
{
if(m_Socket == NULL)
return;
m_Socket->disconnectFromHost();
m_Socket = NULL;
ui->pushButton_connect->setEnabled(true);
ui->pushButton_disconnect->setEnabled(false);
}
void client::on_pushButton_send_clicked()
{
if(!m_Socket)
{
ui->lineEdit_information->clear();
ui->lineEdit_information->setPlaceholderText("没有连接服务器!");
return;
}else if(ui->lineEdit_information->text() == "")
{
ui->lineEdit_information->clear();
ui->lineEdit_information->setPlaceholderText("发送内容为空!");
return;
}
/*取发送信息编辑框内容*/
QString msg = ui->lineEdit_information->text();
/*转编码*/
m_Socket->write(msg.toUtf8());
QDateTime current_date_time =QDateTime::currentDateTime();
QString current_date =current_date_time.toString("hh:mm:ss");
ui->textBrowser->append("发送消息:\t"+current_date);
ui->textBrowser->append(msg);
}
void client::dealreadyRead()
{
QString msg = m_Socket->readAll();
/*获取当前时间*/
QDateTime current_date_time =QDateTime::currentDateTime();
QString current_date =current_date_time.toString("hh:mm:ss");
ui->textBrowser->append("接收消息:\t"+current_date);
ui->textBrowser->append(msg);
}
void client::dealconnected()
{
/*关联数据信号*/
connect(m_Socket,SIGNAL(readyRead()),this,SLOT(dealreadyRead()));
/*检测掉线信号*/
connect(m_Socket,SIGNAL(disconnected()),this,SLOT(dealdisconnected()));
ui->pushButton_connect->setEnabled(false);
ui->pushButton_disconnect->setEnabled(true);
ui->label_status->setText("服务器连接成功!");
}
void client::dealdisconnected()
{
m_Socket = NULL;
ui->label_status->setText("服务器连接断开!");
ui->pushButton_connect->setEnabled(true);
ui->pushButton_disconnect->setEnabled(false);
}