Qt QTcpServer

开发环境 Qt5.5.1、Qt Creator 3.5.1

1、初始化QTcpServer,监听本机指定的端口

void MyTcpServer::init() {
    tcpServer = new QTcpServer();
    if(tcpServer->listen(QHostAddress::Any, SERVER_PORT)) {
        qDebug()<<"tcpServer init";
        connect(tcpServer, SIGNAL(newConnection()), this, SLOT(processNewConnection()));
    } else {
        qDebug()<<tcpServer->errorString();
    }
}

2、处理客户端连接

void MyTcpServer::processNewConnection() {
    qDebug()<<"processNewConnection";
    QTcpSocket* tcpSocket = tcpServer->nextPendingConnection();
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(processDisconnected()));
}

3、从客户端读取数据

void MyTcpServer::processReadyRead() {
    QByteArray rawreply= static_cast<QTcpSocket*>(sender())->readAll();
    qDebug()<<"read : "<<rawreply.data();
}

4、向客户端写数据

MyTcpServer::write(const char* str) {
   QTcpSocket* tcpSocket = static_cast<QTcpSocket*>(sender());
   tcpSocket->open(QTcpSocket::ReadWrite);
   tcpSocket->write(str);
   tcpSocket->flush();
}

5、最后关闭QTcpServer

void MyTcpServer::close() {
   tcpServer->close();
}

注意:以下3个方法必须被声明为槽SLOT

public slots:
    //处理客户端连接
    void processNewConnection();
    //处理读请求
    void processReadyRead();
    //客户端断开连接
    void processDisconnected();

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值