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
  • 相关阅读:
    NYOJ 10 skiing DFS+DP
    51nod 1270 数组的最大代价
    HDU 4635 Strongly connected
    HDU 4612 Warm up
    POJ 3177 Redundant Paths
    HDU 1629 迷宫城堡
    uva 796
    uva 315
    POJ 3180 The Cow Prom
    POJ 1236 Network of Schools
  • 原文地址:https://www.cnblogs.com/wangbin-heng/p/9520567.html
Copyright © 2011-2022 走看看