zoukankan      html  css  js  c++  java
  • Qt网络----简单的TCP

    简易的数据传输:服务器发数据,客户端接收数据(QByteArray类型)

    1、客户端

     1    #include<QtNetwork>
     2     QTcpSocket *socket = new QTcpSocket();
     3     socket->connectToHost("127.0.0.1", 6666);
     4     connect(socket, QTcpSocket::readyRead,
     5             [=]()
     6         {
     7         #if 0
     8             QByteArray buf;
     9             buf=socket->readAll();//接数据
    10             qDebug()<<buf;
    11 #endif
    12 #if 0
    13             QDataStream in(socket);
    14             QString str;
    15             int a;
    16             in>>str>>a;
    17             qDebug()<<"str:"<<str<<"a:"<<a;
    18             #endif
    19         });
    View Code

    2、服务器

     1     #include <QtNetwork>
     2     QTcpServer *tcpServer = new QTcpServer();
     3     tcpServer->listen(QHostAddress::LocalHost, 6666);
     4     connect(tcpServer, &QTcpServer::newConnection,
     5             [=]()
     6         {
     7             QTcpSocket *socket=tcpServer->nextPendingConnection();
     8 #if 0
     9             QByteArray buf="hello Network";
    10             socket->write(buf);
    11 #endif
    12 #if 0
    13             /*不要同时使用,会出错!  可能是黏包,*/
    14             QByteArray buf;
    15             QDataStream out(&buf,QIODevice::WriteOnly);
    16             /*只发送数字123出错。可能是数据太少,或者是需要以字符串开头*/
    17             out<<QString("QDataStream")<<123;
    18             socket->write(buf);
    19 #endif
    20         });
    View Code
  • 相关阅读:
    HDU 1348 Wall
    HDU 2202 最大三角形
    HDU 2215 Maple trees
    HDU 1147 Pick-up sticks
    HDU 1392 Surround the Trees
    风语时光
    HDU 1115 Lifting the Stone
    HDU 1086 You can Solve a Geometry Problem too
    HDU 2108 Shape of HDU
    HDU 3360 National Treasures
  • 原文地址:https://www.cnblogs.com/wangbin-heng/p/9520567.html
Copyright © 2011-2022 走看看