想实现通过一个线程向server发送字符。搜索了论坛的相关提问,有相似问题但是基本没有很好的解决,请高手指点。
我自己定义了一个类
threa1.h
#include <QThread>
class thread1 : public QThread
{
Q_OBJECT
public:
thread1();
void run();
};
thread1.cpp
thread1::thread1()
{
}
void thread1::run()
{
QTcpSocket *tcpSocket;
tcpSocket = new QTcpSocket();
tcpSocket->connectToHost("127.0.0.1",5001);
//qDebug(tcpSocket->errorString());
qDebug() << "text" << tcpSocket->errorString();
tcpSocket->write("dsds");
qDebug() << "text1:" << tcpSocket->errorString();
}
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindowClass)
{
ui->setupUi(this);
thread1 *Thread1;
Thread1 = new(thread1);
Thread1->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
程序编译没问题,在mainwindow 对其进行了调用,可以和server连接,但server 无法收到字符,qDebug显示没有错。但是把run函数的内容放到主窗口中,就没有这个问题。
[ 此帖被lzhxu在2010-01-18 11:10重新编辑 ]