tcp 服务端
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
QTcpServer* tcpserver = nullptr;
QTcpSocket* _lastclient = nullptr;
bool TcpServer::Open(int port)
{
tcpserver = new QTcpServer(this);
tcpserver->listen(QHostAddress::Any, port);
if (tcpserver->isListening())
{
connect(tcpserver, SIGNAL(newConnection()), this, SLOT(slotTcpNewConnection()));
return true;
}
delete tcpserver;
tcpserver = nullptr;
return false;
}
void TcpServer::slotTcpNewConnection()
{
std::unique_lock<std::mutex> lock(_lockConn);
qDebug("NEW CONNECTION");
QTcpSocket *tcpsocket = tcpserver->nextPendingConnection(); //获取监听到的socket
qDebug() << tcpsocket->peerAddress().toString();
qDebug() << tcpsocket->peerPort();
//连接成功后我们再连接一个信号槽到准备接收信号槽函数中去
connect(tcpsocket, SIGNAL(readyRead()), this, SLOT(slotTcpReadyRead()));
connect(tcpsocket, SIGNAL(disconnected()), this, SLOT(slot_disconnected()));
// m_socketList.push_back(ClientStruct{ GetSName(tcpsocket) , tcpsocket });
_lastclient = tcpsocket;
}
void TcpServer::slotTcpReadyRead()
{
QTcpSocket* socket = (QTcpSocket*)sender();
auto buf = socket->readAll();
}
tcp 客户端
#include <QObject>
#include <QTcpSocket>
typedef std::shared_ptr<QTcpSocket> QTcpSocketPtr;
QTcpSocketPtr m_tcpsocket;
m_tcpsocket = std::make_shared<QTcpSocket>();
connect(m_tcpsocket.get(), SIGNAL(readyRead()), this, SLOT(slotTcpReadyRead()));
connect(m_tcpsocket.get(), SIGNAL(disconnected()), this, SLOT(slot_disconnected()));
void LineTcpClient::slotTcpReadyRead()
{
QByteArray buf = m_tcpsocket->readAll();
}
void LineTcpClient::slot_disconnected()
{
}
bool LineTcpClient::TcpConnect(QString IP, int port)
{
CLOG_INFO("TcpConnect::%s::%d", IP.data(), port);
unique_lock<mutex> lock(m_lock_tcp);
m_tcpsocket->connectToHost(IP, port);
if (!m_tcpsocket->isOpen())
{
CLOG_INFO2("false");
return false;
}
m_tcpsocket->setProxy(QNetworkProxy::NoProxy);
m_tcpsocket->waitForConnected(1000);
auto st1 = m_tcpsocket->state();
if (QAbstractSocket::SocketState::ConnectedState == m_tcpsocket->state())
{
CLOG_INFO2("success");
return true;
}
CLOG_INFO2("fail");
return false;
}
void LineTcpClient::Send(QByteArray datas)
{
{
unique_lock<mutex> lock(m_lock_tcp);
if (!m_tcpsocket->isOpen())
{
return;
}
m_tcpsocket->write(datas);
}
CLOG_DEGBUG2(QString("laser send:%1").arg(QString(datas)));
}