tcp服务器和客户端
服务器:文章来源:https://www.toymoban.com/news/detail-550013.html
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
server=new QTcpServer(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_ptn_open_clicked()
{
quint16 port=ui->lineEdit_port->text().toUInt();
if(server->listen(QHostAddress::Any,port)){
QMessageBox::information(this,"","打开成功");
}else{
QMessageBox::critical(this,"","打开失败");
return;
}
connect(server,&QTcpServer::newConnection,this,&Widget::newconnection_slot);
}
void Widget::newconnection_slot()
{
QTcpSocket *socket=server->nextPendingConnection();
clientVector.push_back(socket);
connect(socket,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}
void Widget::readyRead_slot()
{
for(int i=0;i<clientVector.size();i++){
if(clientVector[i]->state()==0){
clientVector.remove(i);
}
}
for(int i=0;i<clientVector.size();i++){
if(clientVector[i]->bytesAvailable()!=0){
QByteArray msg=clientVector[i]->readAll();
ui->listWidget_show->addItem(QString::fromLocal8Bit(msg));
for(int j=0;j<clientVector.size();j++){
clientVector[j]->write(msg);
}
}
}
}
客户端:文章来源地址https://www.toymoban.com/news/detail-550013.html
#include "second.h"
#include "ui_second.h"
Second::Second(QWidget *parent) :
QWidget(parent),
ui(new Ui::Second)
{
ui->setupUi(this);
connect(socket,&QTcpSocket::connected,this,&Second::connected_slot);
connect(socket,&QTcpSocket::disconnected,this,&Second::disconnected_slot);
connect(socket,&QTcpSocket::readyRead,this,&Second::readyRead_slot);
}
Second::~Second()
{
delete ui;
}
void Second::jump_slot(){
this->show();
}
void Second::on_ptn_connect_clicked()
{
QString ip=ui->lineEdit_ip->text();
quint16 port=ui->lineEdit_port->text().toUInt();
userName=ui->lineEdit_userName->text();
if(ui->ptn_connect->text()=="连接服务器"){
socket->connectToHost(ip,port);
}else{
QString msg=userName+":离开聊天室";
socket->write(msg.toLocal8Bit());
socket->disconnectFromHost();
}
}
void Second::connected_slot()
{
ui->ptn_connect->setText("断开服务器");
QMessageBox::information(this,"","连接成功");
QString msg=userName+":进入聊天室";
socket->write(msg.toLocal8Bit());
}
void Second::disconnected_slot()
{
QMessageBox::information(this,"","您已断开连接");
ui->ptn_connect->setText("断开服务器");
}
void Second::readyRead_slot()
{
if(socket->bytesAvailable()!=0){
QString msg=QString::fromLocal8Bit(socket->readAll());
ui->listWidget_show->addItem(msg);
}
}
void Second::on_ptn_sendmsg_clicked()
{
QString msg=ui->lineEdit_sendmsg->text();
socket->write(msg.toLocal8Bit());
ui->lineEdit_sendmsg->clear();
}
到了这里,关于7.11作业的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!