【QT】使用最少代码实现最简单TCP服务器端客户端聊天功能
server.cpp客户端代码实现
1 #include "server.h" 2 #include "ui_server.h" 3 4 server::server(QWidget *parent) : 5 QWidget(parent), 6 ui(new Ui::server) 7 { 8 ui->setupUi(this);
//设置地址和端口号 9 ui->sIP->setText("127.0.0.1"); 10 ui->sPort->setText("9999"); 11
//建立监听连接 12 tcpserver = new QTcpServer(this); 13 tcpserver->listen(QHostAddress(ui->sIP->text()),ui->sPort->text().toInt()); 14
//如果监听收到信息,打印信息
//建立QTcpSocket信息连接
//将信息显示在record
15 connect(tcpserver,&QTcpServer::newConnection,this,[=](){ 16 conn = tcpserver->nextPendingConnection(); 17 ui->record->append("thers's new connection"); 18 connect(conn,&QTcpSocket::readyRead,this,[=](){ 19 QByteArray array = conn->readAll(); 20 ui->record->append(array); 21 }); 22 }); 23
//点击发送按钮,发送信息 24 connect(ui->send,&QPushButton::clicked,this,[=](){ 25 conn->write(ui->msg->toPlainText().toUtf8().data()); 26 ui->record->append("Me Say: " + ui->msg->toPlainText()); 27 ui->msg->clear(); 28 }); 29 30 } 31 32 server::~server() 33 { 34 delete ui; 35 }
client.cpp端代码实现
1 #include "client.h" 2 #include "ui_client.h" 3 #include <QHostAddress> 4 5 Client::Client(QWidget *parent) : 6 QWidget(parent), 7 ui(new Ui::Client) 8 { 9 ui->setupUi(this); 10 11 ui->sIP->setText("127.0.0.1"); 12 ui->sPort->setText("9999");
//建立信息连接 13 tcpclient = new QTcpSocket(this); 14 tcpclient->connectToHost(QHostAddress(ui->sIP->text()),ui->sPort->text().toInt()); 15
//收到信息,显示在record 16 connect(tcpclient,&QTcpSocket::readyRead,this,[=](){ 17 QByteArray array = tcpclient->readAll(); 18 ui->record->append(array); 19 }); 20
//发送信息,显示在record 21 connect(ui->send,&QPushButton::clicked,this,[=](){ 22 tcpclient->write(ui->msg->toPlainText().toUtf8()); 23 ui->record->append("ME Say: "+ui->msg->toPlainText()); 24 }); 25 } 26 27 Client::~Client() 28 { 29 delete ui; 30 }