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()<
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<
客户端与服务器链接
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
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- Docker应用:容器间通信与Mariadb数据库主从复制
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量
- PMSJ寻平面设计师之现代(Hyundai)
- 太平之莲
- 第326天
- Shell-Bash变量与运算符
- 闲杂“细雨”
- 七年之痒之后
- 深入理解Go之generate