• 5142阅读
  • 2回复

TCP字符串发送 [复制链接]

上一主题 下一主题
离线chgdswc
 
只看楼主 倒序阅读 楼主  发表于: 2011-05-21
服务端:#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程序就直接崩溃了,请大家指教一下。
离线qq526665621

只看该作者 1楼 发表于: 2011-05-23
哥们这个程序存在个错误,就是不能够在不同的主机之间进行通信,不知道你这个实在这个网站上看到的吗,要是的话 是没http://www.yafeilinux.com/有错误的
离线hehui

只看该作者 2楼 发表于: 2011-06-21
看来楼主把重要操作放到析构函数里了~
快速回复
限100 字节
 
上一个 下一个