Qt IPC研究之QLocalServer和QLocalSocket

来源:互联网 发布:ubuntu root切换用户 编辑:程序博客网 时间:2024/05/22 14:01

    在Qt中,提供了多种IPC方法,作者所用的是QLocalServer和QLocalSocket。看起来好像和Socket搭上点边,实则底层是windows的name pipe。这应该是支持双工通信的。

 

QLocalServer用来监听某个管道。可以这样建立一个监听

 

QLocalServer *localServer;

localServer = new QLocalServer(this);

localServer->setMaxPendingConnections(MAX_CONNECTION);

 

if (localServer->listen("commandpipe"))

{

qDebug()<<"listen commandpipe namepipe sucessful.";

}

else

{

qDebug()<<"failed to listen commandpipe. ";

}

 

connect(localServer, SIGNAL(newConnection()), this, SLOT(DealConnection()));

 

void IPCServer::DealConnection()

{

QLocalSocket *socket = localServer->nextPendingConnection();

socket->waitForReadyRead();

 

QDataStream ds(socket);

ds.setVersion(QDataStream::Qt_4_6);

QString qstr;

ds>>qstr;

 

qDebug()<<"Server received: "<<qstr;

qDebug()<<"Server processing...";

 

 

ds<<qstr.append(" processed");

 

qDebug()<<"Server send "<<qstr;

 

}

 

在这里主要采用的是QDataStream读取socket是的内容。读取完了之后,又使用这个socket再把内容转发回去。

 

QLocalSocket这一块包含连接,和发送信息这一块。

QLocalSocket _socket = new QLocalSocket(this);

 

_socket->connectToServer("commandpipe");

qDebug()<<"socket connect to namepipe";

 

QDataStream ds(_socket);

 

ds.setVersion(QDataStream::Qt_4_6);

ds<<QString("hello");

 

_socket->waitForBytesWritten();

 

qDebug()<<"send one command";

 

_socket->waitForReadyRead();

QString bbq;

ds>>bbq;

 

qDebug()<<"received servered "<<bbq;

 

注意,这边我一开始发送的时候是使用的发送char *,但接收的时候却是用QString,结果就不对了。因为QString是unicode编码的。所以出错了。不过现在己经正常了。。。。

 

现在Shark中的Service,IPC,都己经走通了。下面主要还有编码格式,QWebKit模块,数据库模块需要完成。

 

 

原创粉丝点击