文章来源地址https://www.toymoban.com/news/detail-803752.html
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btn_connect_clicked()
{
quint16 port=ui->label_port->text().toUInt();
if(ser->listen(QHostAddress::Any,port))
{
QMessageBox::information(this,"服务器","连接成功");//有客户端连接会发来newconnection
connect(ser,&QTcpServer::newConnection,this,&Widget::slot_newconnection);
}
else
{
QMessageBox::information(this,"服务器","连接失败");
}
}
void Widget::slot_newconnection()
{
QTcpSocket *new_socket=ser->nextPendingConnection();
list_socket.push_back(new_socket);
connect(new_socket,&QTcpSocket::readyRead,this,&Widget::slot_readyread);
}
void Widget::slot_readyread()
{
for(int i=0;i<list_socket.count();i++)
{
if(list_socket.at(i)->state()==0)
{
list_socket.removeAt(i);
}
}
for(int j=0;j<list_socket.count();j++)
{
if(list_socket.at(j)->bytesAvailable()>0)
{
QByteArray msg=list_socket.at(j)->readAll();
ui->listWidget->addItem(QString::fromUtf8(msg));
for(int i=0;i<list_socket.count();i++)
{
list_socket.at(i)->write(msg);
}
}
}
}
文章来源:https://www.toymoban.com/news/detail-803752.html
到了这里,关于1/12作业的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!