今天写了一个小程序,本打算测试如何实现QTcpServer监听两个端口,忙活了将近一天,特来记录一下。
本来以为很简单,创建一个MyThread线程继承自QThread,把QTcpServer tcpserver放在该新建线程中,然后在run方法中进行监听,关联信号和槽函数,下面贴一下原来的代码
创建MyThread线程
class MyThread:public QThread
{
public:
run();
QTcpServer *tcpServer;
private slots:
sendMessage()
}
void MyThread::run()
{
tcpServer = new QTcpServer();
if(!tcpServer->listen(QHostAddress("192.168.1.110"),6666))
{ //监听本地主机的6666端口,如果出错就输出错误信息,并关闭
qDebug() << tcpServer->errorString();
close();
}
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage()));
}
void MyThread:: sendMessage()
{
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
clientConnection->write("woshixiancheng");
}
客户端的代码就不贴出来了,知识读取字符串的函数readall();
上面的程序是一种错误的做法,具体哪个地方不正确,我还没有找出答案,我觉得这种方法理论上应该是正确的,也有可能是我的问题,希望有高手可以告诉一下,再次感谢
下面说一说正确的做法,今天在网上搜索了一天,只能有种work-object的方法,具体也不太明白,首先创建一个类继承自QObject
class MyObject:public QObject
{
Q_OBJECT
QTcpServer *tcpServer1;
private slots:
void sendMessage();
void first();
}; 然后在主函数中填写如下代码 myobj = new MyObject();创建一个对象thread = new QThread();创建一个线程myobj->moveToThread(thread1);move到线程thread中,这样就可以线程中操作thread->start();connect(thread,SIGNAL(started()),myobj,SLOT(first()));关联到槽函数 first代码如下 void MyObject::first(){
tcpServer = new QTcpServer();if(!tcpServer->listen(QHostAddress("192.168.1.110"),6666)){ //监听本地主机的6666端口,如果出错就输出错误信息,并关闭qDebug() << tcpServer1->errorString();}connect(tcpServer1,SIGNAL(newConnection()),this,SLOT(sendMessage()));} sendMessage代码如下
void MyObject::sendMessage(){
QTcpSocket *clientConnection = tcpServer1->nextPendingConnection();clientConnection->write("woshixiancheng1");qDebug() << QThread::currentThreadId();打印当前线程id} 这里就完成了,另一个监听端口我放在主线程中,把如下代码放在主线程中就可以了 定义一个tcpServer1和sendMessage1槽函数 if(!tcpServer1->listen(QHostAddress("192.168.1.110"),7777)){ //监听本地主机的6666端口,如果出错就输出错误信息,并关闭qDebug() << tcpServer->errorString();close();}connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage1()));看一下效果void MyObject::sendMessage1(){
QTcpSocket *clientConnection = tcpServer1->nextPendingConnection();clientConnection->write("woshixiancheng2");qDebug() << QThread::currentThreadId();打印当前线程id}