tcpServer.zip

  • QT之王
    了解作者
  • C/C++
    开发工具
  • 7KB
    文件大小
  • zip
    文件格式
  • 0
    收藏次数
  • 10 积分
    下载积分
  • 2
    下载次数
  • 2020-07-20 10:11
    上传日期
tcpServer基于Qt5开发的tcp服务器
tcpServer.zip
  • tcpServer
  • main.cpp
    182B
  • tcpwidget.ui
    854B
  • tcpserverwidget.h
    595B
  • tcpserverwidget.ui
    900B
  • tcpserverwidget.cpp
    2.4KB
  • tcpServer.pro.user
    23.4KB
  • tcpwidget.cpp
    1.8KB
  • tcpServer.pro
    385B
  • tcpwidget.h
    526B
内容介绍
#include "tcpserverwidget.h" #include "ui_tcpserverwidget.h" tcpServerWidget::tcpServerWidget(QWidget *parent) : QWidget(parent), ui(new Ui::tcpServerWidget) { ui->setupUi(this); server = new QTcpServer; server->listen(QHostAddress::Any,8080); connect(server,SIGNAL(newConnection()),this,SLOT(slotNewConnect())); //server相当于一个餐厅 //客户端通过IP地址找到我餐厅的地址,客户找服务员,有多个服务员,相当于多个 //服务端口 //客户端发起连接申请-->服务器等待连接并接受-->服务器提供端口跟客户端交互 //telnet ip port//telnet 127.0.0.1 8080 //ctrl+] //quit } tcpServerWidget::~tcpServerWidget() { delete ui; } void tcpServerWidget::slotNewConnect() { qDebug()<<"Have a connecting"; if(server->hasPendingConnections()) { socket = server->nextPendingConnection(); connect(socket,SIGNAL(readyRead()),this,SLOT(slotReadData())); connect(socket,SIGNAL(disconnected()),this,SLOT(slotDisconnect())); ListSocket << socket; ui->iplistWidget->addItem(socket->peerAddress().toString()+":"+ QString::number(socket->peerPort())); } } void tcpServerWidget::slotReadData() { //qDebug()<<"Have some message"; //qDebug()<<"Have " << socket->bytesAvailable() << "bytes come:"; // QByteArray ba = socket->readAll(); // qDebug() << ba; foreach(QTcpSocket* cli,ListSocket)//容器遍历 { if(cli->bytesAvailable()>0) { QByteArray ba = cli->readAll(); qDebug() << ba; ui->msglistWidget->addItem(cli->peerAddress().toString()+":"+QString::number(cli->peerPort())+"say:" +QString(ba)); if(ba.toStdString() == "cyy") cli->write("You_are_Handsome.");//写到客户端 } } } void tcpServerWidget::slotDisconnect() { for(int i=0;i<ListSocket.count();i++) { QTcpSocket *cli = ListSocket[i]; if(cli->socketDescriptor() == -1) { qDebug()<<cli->peerAddress() << "had leave"; delete ui->iplistWidget->takeItem(i); ListSocket.removeAt(i); } } } void tcpServerWidget::on_pushButton_clicked() { if(!ui->lineEdit->text().isEmpty()) { QTextStream out(socket); out<<ui->lineEdit->text(); ui->lineEdit->setText(""); } }
评论
    相关推荐