一、了解TCP的通信过程
Qt中封装了TCP协议 QTcpServer类负责服务端:
1、创建QTcpServer对象
2、监听listen需要的参数是地址和端口号
3、当有新的客户端连接成功时会发射newConnection信号
4、在newConnection信号的槽函数中,调用nextPendingConnection函数获取新的连接QTcpSocket对象
5、连接QTcpSocket对象的readyRead信号
6、在readyRead信号的槽函数使用read接收数据
7、调用write成员函数发送数据
QTcpSocket负责客户端
1、创建qTcpSocket对象
2、当对象与Server连接成功时会发射connected信号
3、调用成员函数connectToHost连接服务器,需要的参数是地址和端口号
4、connected信号的槽函数中开启发送数据
5、使用write发送数据,read接收数据
二、实现多人聊天室
支持多人聊天(多个客户端)
每个客户端不仅能显示自己发的,还能收到别的客户端发的
服务端收到所有客户端发的
关键代码
client:
//widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include
#include
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
QTcpSocket* tcpSocket;
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_send_clicked();
void connect_success();
void read_data();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
//widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpSocket = new QTcpSocket;
tcpSocket->connectToHost("192.168.43.4",1234);
connect(tcpSocket,SIGNAL(connected()),this,SLOT(connect_success()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_send_clicked()
{
std::string msg = ui->msg->text().toStdString();
int ret = tcpSocket->write(msg.c_str(),msg.size()+1);
qDebug("--send:%d--",ret);
ui->msg->setText("");
}
void Widget::connect_success()
{
qDebug("success");
ui->send->setEnabled(true);
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(read_data()));
}
void Widget::read_data()
{
char buf[256]={};
tcpSocket->read(buf,sizeof(buf));
ui->textEdit->append(buf);
}
server:
//widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include
#include
#include
#include
using namespace std;
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
QTcpServer* tcpServer;
vector socketArr;
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void new_connect();
void read_data();
//void send_data();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
//widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpServer = new QTcpServer;
tcpServer->listen(QHostAddress("192.168.43.4"),1234);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(new_connect()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::new_connect()
{
qDebug("--new connect--");
QTcpSocket* tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(read_data()));
socketArr.push_back(tcpSocket);
}
void Widget::read_data()
{
for(int i=0; ibytesAvailable())
{
char buf[256] = {};
socketArr[i]->read(buf,sizeof(buf));
char buf2[256] = {};
sprintf(buf2,"%d:%s",i,buf);
ui->textEdit->append(buf2);
for(int j=0; jwrite(buf1,sizeof(buf1));
}
}
}
}