开发环境 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();