QT之服务器与客户端的搭建

【QT之服务器与客户端的搭建】服务器的搭建:
const QString IP = “127.0.0.1”;
QTcpServer *tcp_server;
QTcpSocket *cfd;
tcp_server = new QTcpServer(this);
if(! tcp_server->listen(QHostAddress::LocalHost, SERV_PORT))
{
qDebug()<errorString();
close();
}
connect(tcp_server, SIGNAL(newConnection()), this, SLOT(newconnect())); //等待客户端的链接
QDataStream in(cfd);

in.setVersion(QDataStream::Qt_5_0); /*加密传输*/ if(blocksize == 0) { if(cfd->bytesAvailable() < (int)sizeof(quint16)) { return; } in>>blocksize; }qDebug()<<"**9*"; if(cfd->bytesAvailable() < blocksize) { return; }qDebug()<<"**10*"; in>>message; /*将读到的存入message*/cfd->read((char*)&message,cfd->bytesAvailable());

服务器发送给客户端
message_recv.cmd = 101; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out<<(quint16)0; out<seek(0); out<<(quint16)(block.size()-sizeof(quint16)); cfd->write(block, block.length());

客户端与服务器链接
tcpsocket = new QTcpSocket(this); tcpsocket->abort(); tcpsocket->connectToHost(IP, SERV_PORT);

发送给服务器
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out<<(quint16)0;
out< out.device()->seek(0);
out<<(quint16)(block.size()-sizeof(quint16));
tcpsocket->write(block, block.length());
connect(tcpsocket, SIGNAL(readyRead()), this, SLOT(read_server())); /*接收服务器信息*/

接收服务器的信息
QDataStream in(tcpsocket);
in.setVersion(QDataStream::Qt_4_6); //加密传输 if(blocksize == 0) { if(tcpsocket->bytesAvailable() < (int)sizeof(quint16)) { return; } in>>blocksize; } if(tcpsocket->bytesAvailable() < blocksize) { return; } in>>message; //将读到的存入message

    推荐阅读