服务端:#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
tcpServer = new QTcpServer(this);
if(!tcpServer->listen(QHostAddress::LocalHost,6666))
{ //监听本地主机的6666端口,如果
出错就输出
错误信息,并关闭
qDebug() << tcpServer->errorString();
close();
}
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage()));
}
void Widget::sendMessage()
{
QByteArray block;
QDataStream out(&block,QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_5);
out<<(quint16) 0;
out<<tr("hello tcp!!");
out.device()->seek(0);
out<<(quint16)(block.size() - sizeof(quint16));
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
connect(clientConnection,SIGNAL(disconnected()),clientConnection,SLOT(deleteLater()));
clientConnection->write(block);
clientConnection->disconnectFromHost();
ui->statusLabel->setText("send message successful!!!");
}
客户端:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
tcpSocket = new QTcpSocket(this);
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
this,SLOT(displayError(QAbstractSocket::SocketError)));
}
void Widget::newConnect()
{
blockSize = 0;
tcpSocket->abort();
tcpSocket->connectToHost(ui->hostLineEdit->text(),
ui->portLineEdit->text().toInt());
}
void Widget::readMessage()
{
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_5);
if(blockSize==0)
{
if(tcpSocket->bytesAvailable() < (int)sizeof(quint16)) return;
in >> blockSize;
}
if(tcpSocket->bytesAvailable() < blockSize) return;
in >> message;
ui->messageLabel->setText(message);
}
void Widget::displayError(QAbstractSocket::SocketError)
{
qDebug() << tcpSocket->errorString();
}
void Widget::on_pushButton_clicked()
{
newConnect();
}
出来的程序是这样的:
可以不知道为什么一点PushButton程序就直接崩溃了,请大家指教一下。