标签:qt tcp
服务器:
#include "server.h"
#include "ui_server.h"
Server::Server(QWidget *parent) :
QWidget(parent),
ui(new Ui::Server)
{
m_tcpServer = new QTcpServer(this); //注意,这里的变量是在.h文件中声明的,是一个指针,在头文件中应该包含QTcpServer 这个类,而且在工程文件中应该加入相应的network;
connect(m_tcpServer, SIGNAL(newConnection()),
this, SLOT(serverConnected()));
m_tcpServer->listen(QHostAddress::Any, 666); //监听来自各种ip传来的数据;
ui->setupUi(this);
}
Server::~Server()
{
delete ui;
}
void Server::serverConnected()
{
QTcpSocket *connection = m_tcpServer->nextPendingConnection(); //通过nextPendingConnection方法获取连接的对象
connect(connection, SIGNAL(disconnected()),connection, SLOT(deleteLater()));
QByteArray buffer;
//...
QDataStream out(&buffer, QIODevice::WriteOnly); // 用于建立缓冲区和socket的对应关系;
out.setVersion(QDataStream::Qt_4_6);
QString greeting = QString("Hello! The time is %1").arg(QTime::currentTime().toString());
out << (quint16)0; //在这里,这一位准备保存有效数据这长度,这里先占用一位,到数据输入完成后,统计长度,并且给其赋值;
out << greeting;
out.device()->seek(0); //将指针移动到下标为零的数组出,准备存放有效数据的长度;
out << (quint16)(buffer.size() - sizeof(quint16)); //计算有效数据的长度,用总长度减去第一位的长度;
connection->write(buffer); //把缓冲区里的数据写到connection(这是一个QTcpSocket对象);
connection->disconnectFromHost(); //断开连接;
}
客户端:
#include "client.h"
#include "ui_client.h"
#include <QDebug>
Client::Client(QWidget *parent) :
QWidget(parent),
ui(new Ui::Client)
{
m_tcpBlockSize = 0;
m_tcpSocket = new QTcpSocket(this);这里的变量是在.h文件中声明的,是一个指针,在头文件中应该包含QTcpServer 这个类,而且在工程文件中应该加入相应的network;
connect(m_tcpSocket, SIGNAL(readyRead()),
this, SLOT(readyToRead()));
m_tcpSocket->connectToHost("localhost", 666); //localhost可以使具体的ip地址;
ui->setupUi(this);
}
Client::~Client()
{
delete ui;
}
void Client::readyToRead()
{
QDataStream in(m_tcpSocket);
in.setVersion(QDataStream::Qt_4_6); //使用了QDataStream类,就要对QT版本进行强制设定
if(m_tcpBlockSize == 0) //还是不太理解这个变量在这里判断的作用;
{
if(m_tcpSocket->bytesAvailable()<sizeof(quint16)) //当未读的有效字节数小于数据流中靠前的用于保存数据长度的字节数时,则停止;
return;
in >> m_tcpBlockSize; //否则,将输入流的靠前的用于存放有效字节数大小的内容存放到m_tcpBlockSize中;
}
if(m_tcpSocket->bytesAvailable() < m_tcpBlockSize) //当未读的有效字节数小于 字节流中标志的字节数时,停止,(因为数据错误,必须保证数据的完整性);
return;
QString greeting;
in >> greeting; //把收到的有效数据放到greeting中,下面用qDebug打印出来;
//doSomething(greeting);
qDebug() << "receive data: " << greeting;
m_tcpBlockSize = 0;
}
这里仅仅写了.cpp文件,其他文件比较简单,读者应该可以完成;
这里要注意,通信双方有服务器和客户端之分;
这只是TCP通信的基本实验,是后续实验的基础;
昨天是个意外,没有写博客,今天是第四天:
弟子规:
冬则温 夏则凊 晨则省 昏则定
出必告 反必面 居有常 业无变标签:qt tcp
原文地址:http://10901086.blog.51cto.com/10891086/1876941