例子为Server发送数据给Client,Client处理后返回数据给Server
1.Server
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void newConnect();
void readMessage();
void onClick();
void displayError(QAbstractSocket::SocketError);
private:
Ui::Widget* ui;
QTcpServer* tcpServer;
QTcpSocket* tcpSocket;
};
Widget::Widget(QWidget* parent):
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
if(!tcpServer->listen(QHostAddress("10.2.100.67"),80))
{
QString error = tcpServer->errorString();
std::cout<<"error:"<<qPrintable(error)<<std::endl;
close();
}
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnect()));
connect(ui->ok,SIGNAL(clicked()),this,SLOT(onClick()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::readMessage()
{
QString tag = tcpSocket->read(6);
std::cout<<"result:"<<qPrintable(tag)<<std::endl;
}
void Widget::displayError(QAbstractSocket::SocketError)
{
}
void Widget::newConnect()
{
std::cout<<"connect."<<std::endl;
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
}
void Widget::onClick()
{
if(!tcpSocket)
return;
std::cout<<"send data:"<<std::endl;
QByteArray block;
QString tag("6");
block.append(tag);
block.append(",");
for(int i=0;i<6;i++)
{
block.append("123456");
block.append(",");
}
block = block.mid(0,block.size()-1);
tcpSocket->write(block);
ui->content->setPlainText("send success");
}
Client
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void readMessage();
void displayError(QAbstractSocket::SocketError);
void sendMessage();
private:
QTcpSocket* tcpsocket;
QString message;
QPushButton* button;
};
Widget::Widget(QWidget* parent):
QWidget(parent)
{
button = new QPushButton("Send");
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(button);
connect(button,SIGNAL(clicked()),this,SLOT(sendMessage()));
tcpsocket = new QTcpSocket(this);
tcpsocket->abort();
tcpsocket->connectToHost("10.2.100.67",80);
connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
connect(tcpsocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
}
Widget::~Widget()
{
}
void Widget::readMessage()
{
QString tag = tcpsocket->read(1);
int count = tag.toInt();
if(count > 0)
{
std::cout<<"data length:"<<count<<std::endl;
int i = 0;
QString data;
while(true)
{
QString block = tcpsocket->read(60);
if(block.isEmpty())
break;
data += block;
i ++;
}
data = data.mid(1);
QStringList list = data.split(",");
foreach(QString item,list)
std::cout<<qPrintable(item)<<std::endl;
}
}
void Widget::displayError(QAbstractSocket::SocketError)
{
qDebug() << tcpsocket->errorString();
}
void Widget::sendMessage()
{
std::cout<<"write callback data."<<std::endl;
tcpsocket->write("ok");
}