QT实现TCP服务器客户端的搭建
服务器代码:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
server = new QTcpServer(this);
connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
Widget::~Widget()
{
delete ui;
}
//启动按钮的槽函数
void Widget::on_startBtn_clicked()
{
quint16 port=ui->portEdit->text().toUInt();
if(server->listen(QHostAddress::Any,port))
{
QMessageBox::information(this,"失败","监听失败");
return ;
}else
{
QMessageBox::information(this,"成功","服务器监听成功");
return ;
}
}
void Widget::newConnection_slot()
{
qDebug()<<"您有新的客户端请求";
QTcpSocket *s=server->nextPendingConnection();
clientList.push_back(s);
connect(s,&QTcpSocket::readyRead,this,& Widget::readyRead_slot);
}
void Widget::readyRead_slot()
{
qDebug("有新消息发来了");
for(int i=0;i<clientList.size();i++)
{
if(clientList[i]->state()==0)
{
clientList.removeAt(i);
}
}
for(int i=0;i<clientList.size();i++)
{
if(clientList[i]->bytesAvailable()!=0)
{
QByteArray msg=clientList[i]->readAll();
ui->msgWidget->addItem(QString::fromLocal8Bit(msg));
for(int j=0;j<clientList.size();j++)
{
clientList[j]->write(msg);
}
}
}
}
客户端代码:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
socket =new QTcpSocket(this);
connect(socket,&QTcpSocket::connected,this,&Widget::connected_slot);
connect(socket,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
connect(socket,&QTcpSocket::disconnected,this,&Widget::disconnected_slot);
}
Widget::~Widget()
{
delete ui;
}
//连接服务器按钮
void Widget::on_connectBtn_clicked()
{
userName =ui->userNameEdit->text();
QString ip=ui->ipEdit->text();
quint16 port = ui->portEdit->text().toUInt();
socket->connectToHost(ip,port);
}
void Widget::connected_slot()
{
QMessageBox::information(this,"成功","您已经成功进入聊天室");
QString msg=userName + ":进入聊天室";
socket->write(msg.toLocal8Bit());
}
void Widget::readyRead_slot()
{
QByteArray msg=socket->readAll();
ui->msgWidget->addItem(QString::fromLocal8Bit(msg));
}
void Widget::on_sendBtn_clicked()
{
QString msg=userName+":"+ui->msgedit->text();
socket->write(msg.toLocal8Bit());
ui->msgedit->clear();
}
void Widget::on_disconnectBtn_clicked()
{
QString msg =userName+":我走了哈,我不打扰";
socket->write(msg.toLocal8Bit());
socket->disconnectFromHost();
}
void Widget::disconnected_slot()
{
QMessageBox::information(this,"提示","退出成功");
}