Qt的网络通信(以一对一聊天室为例)
一、以一对一(服务器,客户端)为例
1、服务器:
1、在目录文件 .pro文件中 QT += core gui network 添加network
2、在.h 文件中,定义
QTcpServer* server;
QTcpSocket* socket; 记得添加头文件
3、 ui->setupUi(this);
server = new QTcpServer;
server->listen(QHostAddress::Any,1111);//等待连接
connect(server,SIGNAL(newConnection()),this,SLOT(new_connect()));//记得添加槽信号
4、//找到与服务器链接的客户端
void MainWindow::new_connect()
{
socket = server->nextPendingConnection();
connect(socket,SIGNAL(readyRead()),this,SLOT(ready_read()));
ui->pushButton->setEnabled(true);
}
5、
void MainWindow::ready_read()
{
socket->read(buf,sizeof(buf));
ui->read_listWidget->addItem(buf);
}
6、
void MainWindow::on_pushButton_clicked()
{
socket->write(ui->lineEdit->text().toStdString().c_str(),ui->lineEdit->text().length());//发送内容给客户端
ui->read_listWidget->addItem("server:"+ui->lineEdit->text());
ui->lineEdit->setText(" ");\\清空写的内容
}
2、客户端 (是通过IP地址和端口号来进行连接的)
1、+network
2、定义socket
3、
void MainWindow::on_conncet_buf_clicked()
{
socket->connectToHost(ui->lineEdit_2->text(),ui->lineEdit_3->text().toUInt());
connect(socket,SIGNAL(readyRead()),this,SLOT(ready_read()));
}
4、
void MainWindow::ready_read()
{
char buf[255] = {};
socket->read(buf,sizeof(buf));
ui->read_listWidget->addItem(buf);
}
5、void void MainWindow::on_send_btn_clicked()
{
socket->write(ui->lineEdit->text().toStdString().c_str(),buf+ui->lineEdit->text().toAscii().length());//文字输出,要在mian.c中添加对中文的处理;
ui->read_listWidget->addItem(buf+ui->lineEdit->text());
ui->lineEdit->setText(" ");
}