24,860
社区成员




void TcpServer::incomingConnection(int socketDescriptor)
{
TcpSocket *tcpSocket = new TcpSocket(this);
connect(tcpSocket, SIGNAL(updateClients(QString,int)),
this, SLOT(updateClients(QString,int)));
connect(tcpSocket, SIGNAL(disconnected(int)),
this, SLOT(tcpDisconnected(int)));
tcpSocket->setSocketDescriptor(socketDescriptor);
tcpSocketList.append(tcpSocket);
//在list末尾插入数据
return emit QTcpServer::newConnection ();
}
TcpServer::TcpServer(QObject *parent, int port) :
QTcpServer(parent)
{
if(this->listen (QHostAddress::Any,port))
{
qDebug("invocation!!!");
}
else
{
qDebug("disinvocation!!!");
}
//监听本机的IP地址和端口
}
tcpSocket->connectToHost(ipAddress, port);
也成功连接了,但是incomingConnection()并没有执行。#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QTcpSocket>
#include <QDebug>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(int ID, QObject *parent = 0);
int ID;
void run();
struct messge_test
{
std::string SN;
std::string IP;
std::string Condition;
};//message_rev;
quint16 nextBlockSize;
signals:
void error(QTcpSocket::SocketError socketerror);
public slots:
void readyRead();
void disconnected();
private:
QTcpSocket *socket;
int socketDescriptor;
};
#endif // MYTHREAD_H
#include "mythread.h"
MyThread::MyThread(int ID , QObject *parent) :
QThread(parent)
{
this->socketDescriptor = ID;
}
void MyThread::run()
{
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
exec();
}
void MyThread::readyRead()
{
messge_test *message_rev;
QByteArray data = socket->readAll();
message_rev = (messge_test*)data.data();
qDebug()<<"data:"<<data.data();
}
void MyThread::disconnected()
{
socket->deleteLater();
exit(0);
}
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QDebug>
#include <QTcpServer>
class MyServer : public QTcpServer
{
Q_OBJECT
public:
explicit MyServer(QObject *parent = 0);
void startServer();
signals:
public slots:
protected:
void incomingConnection(int socketDescriptor);
};
#endif // MYSERVER_H
#include "myserver.h"
#include "mythread.h"
MyServer::MyServer(QObject *parent) :
QTcpServer(parent)
{
}
void MyServer::startServer()
{
int port = 6666;
if(!this->listen(QHostAddress::Any, port))
{
qDebug() << "Could not start server";
}
else
{
qDebug() << "Listening to port " << port << "...";
}
}
void MyServer::incomingConnection(int socketDescriptor)
{
qDebug()<<"incomingconnection!";
MyThread *thread = new MyThread(socketDescriptor, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}