• QtSocket(转)


     
    转自
    http://blog.csdn.net/kusey/article/details/6800325
     
    分类: socket qt 245人阅读 评论(1) 收藏 举报

             刚接触 Qt 网络编程这一块,以下是一个简单的 tcp 通信流程,里面还有很多东西没有弄懂,难免有错误存在,在这里先做记录,以后弄懂了再做改正。

    服务器端代码:

    chat_server.h

    1. #ifndef __chat_server_h__  
    2. #define __chat_server_h__  
    3.   
    4. #include <QTcpServer>  
    5.   
    6. class MySocket;  
    7.   
    8. class ChatServer : public QTcpServer  
    9. {  
    10.     Q_OBJECT  
    11.   
    12. public:  
    13.     ChatServer  ( QObject *parent = NULL );  
    14.     ~ChatServer ();  
    15.   
    16.     void    Run ( quint16 port );  
    17.   
    18. protected:  
    19.     void    incomingConnection  ( int handle );  
    20.   
    21. private slots:  
    22.     void    clientDisconnected  ();  
    23.   
    24. private:  
    25.     quint16             _port;  
    26.     QList<MySocket*>  _mysockets;  
    27. };  
    28.   
    29. #endif // __chat_server_h__  


    chat_server.cpp

    1. #include "chat_server.h"  
    2. #include "my_socket.h"  
    3. #include <QHostAddress>  
    4.   
    5. ChatServer::ChatServer( QObject *parent /* = NULL */ )  
    6.     : QTcpServer( parent )  
    7. {  
    8.     _mysockets.empty();  
    9. }  
    10.   
    11. ChatServer::~ChatServer()  
    12. {  
    13.     qDeleteAll( _mysockets );  
    14.     _mysockets.clear();  
    15. }  
    16.   
    17. void ChatServer::Run( quint16 port )  
    18. {  
    19.     if( !this->listen(QHostAddress::Any, port) )  
    20.         printf( "ChatServer listen failed !" );  
    21. }  
    22.   
    23. void ChatServer::incomingConnection( int handle )  
    24. {  
    25.     printf( "incomingConnection(): %d !\n", handle );  
    26.     MySocket *mysocket = new MySocket( this );  
    27.     mysocket->setSocketDescriptor( handle );  
    28.     connect( mysocket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()) );  
    29.     _mysockets.append( mysocket );  
    30. }  
    31.   
    32. void ChatServer::clientDisconnected()  
    33. {  
    34.     printf( "client disconnected !\n" );  
    35.     QList<MySocket*>::iterator iter;  
    36.     for( iter = _mysockets.begin(); iter != _mysockets.end(); iter++ ) {  
    37.         if( -1 == (*iter)->socketDescriptor() ) {  
    38.             _mysockets.erase( iter );  
    39.             return;  
    40.         }  
    41.     }  
    42. }  


    my_socket.h

    1. #ifndef __my_socket_h__  
    2. #define __my_socket_h__  
    3.   
    4. #include <QThread>  
    5. #include <QTcpSocket>  
    6.   
    7. class ChatServer;  
    8.   
    9. class MySocket : public QTcpSocket  
    10. {  
    11.     Q_OBJECT  
    12.   
    13. public:  
    14.     MySocket    ( QObject *parent = NULL );  
    15.     ~MySocket   ();  
    16.   
    17. private slots:  
    18.     void    onReadyRead     ();  
    19. };  
    20.   
    21. #endif // __my_socket_h__  


    my_socket.cpp

    1. #include "my_socket.h"  
    2. #include "chat_server.h"  
    3. #include <QTcpSocket>  
    4.   
    5. MySocket::MySocket( QObject *parent /* = NULL */ )  
    6.     : QTcpSocket( parent )  
    7. {  
    8.     connect( this, SIGNAL(readyRead()), this, SLOT(onReadyRead()) );  
    9. }  
    10.   
    11. MySocket::~MySocket()  
    12. {  
    13.     printf( "~MySocket\n" );  
    14.     close();  
    15. }  
    16.   
    17. void MySocket::onReadyRead()  
    18. {  
    19.     char data[1024] = { 0 };  
    20.     int len = readData( data, 1024 );  
    21.     if( len <= 0 ) {  
    22.         printf( "MySocket::OnReadyRead() read data failed !\n" );  
    23.         return;  
    24.     }  
    25.   
    26.     printf( "receive data: %s\n", data );  
    27.   
    28.     if( 0 >= writeData(data, len) )  
    29.         printf( "MySocket::OnReadyRead() write data failed !\n" );  
    30.     else  
    31.         printf( "send    data: %s\n", data );  
    32. }  


    main.cpp

    1. #include "chat_server.h"  
    2. #include <QtCore/QCoreApplication>  
    3.   
    4. int main(int argc, char *argv[])  
    5. {  
    6.     QCoreApplication a(argc, argv);  
    7.   
    8.     ChatServer server;  
    9.     server.Run( 33333 );  
    10.   
    11.     return a.exec();  
    12. }  


    客户端代码:

    chat_client.h

    1. #ifndef __chat_client_h__  
    2. #define __chat_client_h__  
    3.   
    4. #include <QTcpSocket>  
    5.   
    6. class ChatClient : public QTcpSocket  
    7. {  
    8.     Q_OBJECT  
    9.   
    10. public:  
    11.     ChatClient  ( QObject *parent = NULL );  
    12.     ~ChatClient ();  
    13.   
    14.     void    ConnectToServer ( const char *ip, quint16 port );  
    15.     void    Close           ();  
    16.     bool    WriteData       ( const char *data, qint64 len );  
    17.   
    18. protected:  
    19.     void    ParseData   ( const char *data, qint64 len );  
    20.   
    21. private slots:  
    22.     void    OnConnected ();  
    23.     void    OnReadyRead ();  
    24.   
    25. private:  
    26.     enum { BUFFERSIZE_MAX = 1024 };  
    27. };  
    28.   
    29. #endif // __chat_client_h__  


    chat_client.cpp

    1. #include "chat_client.h"  
    2. #include <QHostAddress>  
    3.   
    4. ChatClient::ChatClient( QObject *parent /* = NULL */ )  
    5.     : QTcpSocket( parent )  
    6. {  
    7.     connect( this, SIGNAL(readyRead()), this, SLOT(OnReadyRead()) );  
    8.     connect( this, SIGNAL(connected()), this, SLOT(OnConnected()) );  
    9. }  
    10.   
    11. ChatClient::~ChatClient()  
    12. {  
    13. }  
    14.   
    15. void ChatClient::ConnectToServer( const char *ip, quint16 port )  
    16. {  
    17.     QString strip( ip );  
    18.     QHostAddress addr;  
    19.     addr.setAddress( strip );  
    20.     connectToHost( addr, port );  
    21. }  
    22.   
    23. void ChatClient::Close()  
    24. {  
    25.     disconnectFromHost();  
    26.     close();  
    27. }  
    28.   
    29. bool ChatClient::WriteData( const char *data, qint64 len )  
    30. {  
    31.     if( NULL == data || len <= 0 )  
    32.         return false;  
    33.     qint64 ret = writeData( data, len );  
    34.     if( 0 >= ret )  
    35.         return false;  
    36.   
    37.     waitForBytesWritten( -1 );                  // why ?  
    38.     printf( "send    data: %s\n", data );  
    39.   
    40.     waitForReadyRead( -1 );                     // why ?  
    41.   
    42.     return true;  
    43. }  
    44.   
    45. void ChatClient::ParseData( const char *data, qint64 len )  
    46. {  
    47.     printf( "receive data: %s\n", data );  
    48. }  
    49.   
    50. void ChatClient::OnReadyRead()  
    51. {  
    52.     char data[BUFFERSIZE_MAX] = { 0 };  
    53.     qint64 len = readData( data, BUFFERSIZE_MAX );  
    54.     if( len <= 0 )  
    55.         return;  
    56.     else  
    57.         ParseData( data, len );  
    58. }  
    59.   
    60. void ChatClient::OnConnected()  
    61. {  
    62.     printf( "connected: %d !\n", socketDescriptor() );  
    63. }  


    main.cpp

      1. #include "chat_client.h"  
      2. #include <QtCore/QCoreApplication>  
      3.   
      4. int main(int argc, char *argv[])  
      5. {  
      6.     QCoreApplication a(argc, argv);  
      7.   
      8.     ChatClient  client;  
      9.     char        ip[16]  = { 0 };  
      10.     quint16     port    = 0;  
      11.   
      12.     client.ConnectToServer( "127.0.0.1", 33333 );  
      13.     client.waitForConnected( -1 );  
      14.   
      15.     char        msg[1024]   = { 0 };  
      16.     printf( "please input message(exit with 'exit'): \n" );  
      17.     while( 1 ) {  
      18.         gets( msg );  
      19.         if( 0 == strcmp(msg, "exit") )  
      20.             break;  
      21.   
      22.         if( !client.WriteData(msg, strlen(msg) + 1) ) {  
      23.             printf( "WriteData failed !\n" );  
      24.             break;  
      25.         }  
      26.     }  
      27.   
      28.     client.Close();  
      29.   
      30.     return a.exec();  

  • 相关阅读:
    go学习中的零散笔记
    git reset --hard与git reset --soft的区别
    php必学必会
    gdb 解core
    php学习
    高仿京东到家APP引导页炫酷动画效果
    RxHttp
    SVN回滚文件
    遍历枚举
    python3 多线程
  • 原文地址:https://www.cnblogs.com/ljjphysics/p/2470670.html
Copyright © 2020-2023  润新知