客户端连接服务器后,一般是单独启动一个线程。用来监听客户端发来的信息。
.h
#ifndef MYTCPSERVER_H
#define MYTCPSERVER_H
#include <QTcpServer>
#include"thread_recv_tcp.h"
#include"Thread_server.h"
class MyTcpServer : public QTcpServer
{
Q_OBJECT
public:
MyTcpServer();
explicit MyTcpServer(QObject *parent = 0);
protected:
void incomingConnection(int socketDescriptor);
private:
Thread_server* thread_service;
Thread_recv_tcp* thread_recv;
};
#endif // MYTCPSERVER_H
.cpp
#include "mytcpserver.h"
#include <QDebug>
MyTcpServer::MyTcpServer()
{
}
MyTcpServer::MyTcpServer(QObject *parent)
:QTcpServer(parent) {
}
void MyTcpServer::incomingConnection(int socketDescriptor){
qDebug()<<"新的连接...";
thread_recv = new Thread_recv_tcp(socketDescriptor, this);
thread_recv -> start();
//开启解析线程
thread_service = new Thread_server();
thread_service->start();
}
监听接收数据的线程:
#ifndef THREAD_RECV_TCP_H
#define THREAD_RECV_TCP_H
#include<QThread>
#include<QTcpSocket>
class Thread_recv_tcp : public QThread
{
Q_OBJECT
public:
Thread_recv_tcp();
Thread_recv_tcp(int socketDescriptor, QObject *parent);
~Thread_recv_tcp();
protected:
void run();
private slots:
void readMessage();
private:
private:
volatile bool m_stopped;
int m_socketDescriptor;
};
#endif // THREAD_RECV_TCP_H
#include "thread_recv_tcp.h"
#include"lcss_global.h"
Thread_recv_tcp::Thread_recv_tcp(){
m_stopped = false;
}
Thread_recv_tcp::Thread_recv_tcp(int socketDescriptor, QObject *parent)
:QThread(parent),m_socketDescriptor(socketDescriptor) {
}
Thread_recv_tcp::~ Thread_recv_tcp(){
quit();
}
void Thread_recv_tcp::run(){
qDebug()<<"线程启动...";
g_Socket = new QTcpSocket();
//将Server传来的socketDescriptor与刚创建的tcpSocket关联
if (!g_Socket->setSocketDescriptor(m_socketDescriptor)) {
// emit error(g_Socket->error());
return;
}
qDebug()<<m_socketDescriptor;
connect(g_Socket, SIGNAL(readyRead()),this, SLOT(readMessage()),Qt::BlockingQueuedConnection);
exec();
}
void Thread_recv_tcp::readMessage() //读取信息
{
QByteArray qba = g_Socket -> readAll();
qDebug()<<qba;
QString ss = QVariant(qba).toString();
g_mutex.lock();
g_msg_queue.push(qba);
g_mutex.unlock();
// ui->textEditSvrMsg->setText(ss);
}
使用:
MyTcpServer* m_MyTcpServer;
m_MyTcpServer = new MyTcpServer(this);
if(m_MyTcpServer->isListening()){
return;
}
//需要开启监听
//获取端口
int nPort = ui->lineEditPort->text().toInt();
bool bres = m_MyTcpServer->listen(QHostAddress::Any, nPort);
if(bres){
//成功
QMessageBox::information(this, tr("Listen"), tr("Listen successed."));
return;
}else{
//失败
QMessageBox::warning(this, tr("Listen"), tr("Listen failed."));
return;
}