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 });
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 });