09_TCP客户服务端

    • 一服务端
    • 二客户端

一、服务端

#include "TcpServer.h"


TcpServer::TcpServer(QWidget *parent):QWidget(parent) { 

    _Server = new QTcpServer ;
    _Port = 9988 ;
    //1、将服务器的ip和端口绑定好
    _Server->listen( QHostAddress::Any , _Port )  ;
    //2、如果有连接进来,则调用下面的函数slotConnectNetwork
    _Server->connect( _Server , SIGNAL( newConnection() ) , this , SLOT(slotConnectNetwork()) ) ;

    QHBoxLayout *layout = new QHBoxLayout(this) ;
    layout->addWidget( _Show = new QTextBrowser ) ;
    _Show->append( "Bind . Listen succeed ..." ) ;
}


void TcpServer::slotConnectNetwork(){

    /*判断是否有未连接的处理*/
    /*这里也是一样,如果有未连接没被处理,下次客户端连接上来是不进行处理的*/
    while( _Server->hasPendingConnections() ) { 
        // 3、调用nextPeddingConnection去获得连接的socket
        QTcpSocket *socket = _Server->nextPendingConnection() ;
        _Show->append( "Someone to connect..." ) ;
        _Sockets.push_back( socket ) ;//这个是担心这里的临时变量socket会失效才创建的。
        // 4、为新的socket提供槽函数,来接收数据
        //注意:这里相当于给当前这个客户socket创建了一个read线程
        connect( socket , SIGNAL( readyRead() ) , this , SLOT( slotReadyRead()) ) ;
    }
}


void TcpServer::slotReadyRead() {

    // 接收数据,判断是否有数据,如果有,通过readAll函数获取所有数据
    //如果没将数据接收完,则是继续读取下次客户端发送过来数据的
    QTcpSocket *socket = (QTcpSocket*)QObject::sender() ;
    while( socket->bytesAvailable()>0 ) {
        QByteArray buf = socket->readAll() ;
        _Show->append( "receive is : "+buf ) ;
        socket->write( "nice" ) ;
    }
}


void TcpServer::paintEvent(QPaintEvent *){

    QPainter painter(this) ;
    painter.setBrush( Qt::yellow ) ;
    painter.drawRect( 0 , 0 , this->width() , this->height() ) ;
}


TcpServer::~TcpServer(void) { 

    /*记得释放资源*/
}

二、客户端

#include "TcpClient.h"


TcpClient::TcpClient( QWidget *parent ):QWidget( parent ) {

    _Socket = new QTcpSocket(this) ;
    _Socket->connectToHost( "127.0.0.1" , 9988 ) ;
    _Layout = new QHBoxLayout(this) ;

    _Layout->addWidget( _Lineedit = new QLineEdit ) ;
    _Layout->addWidget( _Button = new QPushButton( "send" ) ) ;
    _Layout->addWidget( _Label = new QLabel( "receiver" ) ) ;

    connect( _Lineedit , SIGNAL( returnPressed() ) , this , SLOT( slotReturnPressed() ) ) ;
    //客户端write,回车或是btn直接将信息传给服务器
    connect( _Button , SIGNAL( clicked() ) , this , SLOT(slotReturnPressed())); 
    //客户端read,为socket提供槽函数,来接收数据
    connect( _Socket , SIGNAL( readyRead() ) , this , SLOT( slotReadyRead()) ) ;
}


void TcpClient::slotReadyRead(){


    while( _Socket->bytesAvailable()>0 ) {
        QByteArray buf = _Socket->readAll() ;
        _Label->setText( "receive is : "+buf ) ;
    }
}


void TcpClient::slotReturnPressed(){

    qDebug() << _Socket->ConnectedState ;
    QString strText = _Lineedit->text() ;
    if(strText.isEmpty())
        return;

    _Socket->write(strText.toUtf8());
    _Lineedit->clear();
}


TcpClient::~TcpClient(void) { 

    /*记得释放资源*/
}



你可能感兴趣的:(tcp,QT)