Qt QTcpServer
【摘要】
开发环境 Qt5.5.1、Qt Creator 3.5.1
1、初始化QTcpServer,监听本机指定的端口
void MyTcpServer::init() {
tcpServer = new QTcpServer();
if(tcpServer->listen(QHostAddress::Any, ...
开发环境 Qt5.5.1、Qt Creator 3.5.1
1、初始化QTcpServer,监听本机指定的端口
void MyTcpServer::init() {
tcpServer = new QTcpServer();
if(tcpServer->listen(QHostAddress::Any, SERVER_PORT)) {
qDebug()<<"tcpServer init";
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(processNewConnection()));
} else {
qDebug()<<tcpServer->errorString();
}
}
2、处理客户端连接
void MyTcpServer::processNewConnection() {
qDebug()<<"processNewConnection";
QTcpSocket* tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(processDisconnected()));
}
3、从客户端读取数据
void MyTcpServer::processReadyRead() {
QByteArray rawreply= static_cast<QTcpSocket*>(sender())->readAll();
qDebug()<<"read : "<<rawreply.data();
}
4、向客户端写数据
MyTcpServer::write(const char* str) {
QTcpSocket* tcpSocket = static_cast<QTcpSocket*>(sender());
tcpSocket->open(QTcpSocket::ReadWrite);
tcpSocket->write(str);
tcpSocket->flush();
}
5、最后关闭QTcpServer
void MyTcpServer::close() {
tcpServer->close();
}
注意:以下3个方法必须被声明为槽SLOT
public slots:
//处理客户端连接
void processNewConnection();
//处理读请求
void processReadyRead();
//客户端断开连接
void processDisconnected();
文章来源: blog.csdn.net,作者:福州-司马懿,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/chy555chy/article/details/51440643
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)