实现服务器端和客户端,接收方式均采用槽接收方式,过程中可F1 F2查看官方文档
服务端
新建类,选择基类
源文件
.h文件
#ifndef SOCKET_H
#define SOCKET_H
#include <QObject>
#include <qtcpserver.h>
#include <qtcpsocket.h>
class socket : public QObject
{
Q_OBJECT
public:
explicit socket(int port,QObject *parent = nullptr);
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
void WriteData(QByteArray bytes);
public slots:
void acceptConnection();
void readData();
};
#endif // SOCKET_H
.cpp文件
#include "socket.h"
socket::socket(int port, QObject *parent) : QObject(parent)
{
tcpServer = new QTcpServer();
tcpServer->listen(QHostAddress::Any,port);
tcpSocket = nullptr;
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection()));
}
void socket::acceptConnection(){
qDebug()<<"connect";
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readData()));
connect(tcpSocket, &QAbstractSocket::disconnected,tcpSocket, &QObject::deleteLater);
}
void socket::readData(){
QByteArray bytes = tcpSocket->readAll();
qDebug()<<bytes;
}
void socket::WriteData(QByteArray bytes){
if(tcpSocket->isOpen()){
tcpSocket->write(bytes);
}
}
需要注意的点
- 需要引用两个头文件qtcpserver.h 和 qtcpsocket.h,两个里面包含了服务端和客户端
- 服务端等待连接,有连接过来需要使用socket来进行通讯,里面readyData信号
- 使用方式在主界面初始化时,socket *m = new socket(6789);
客户端
新建类,选择基类,和服务端一样
源文件
.cpp
#include "socket.h"
#include "servo.h"
#include "vrep.h"
socket::socket(QObject *parent) : QObject(parent)
{
tcpSocket = new QTcpSocket(parent);
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readData()));
}
void socket::ConnectServer(const QString &hostName,int port){
tcpSocket->connectToHost(hostName,port);
}
void socket::readData(){
QByteArray bytes = tcpSocket->readAll();
qDebug()<<bytes;
}
void socket::WriteData(QByteArray bytes){
if(tcpSocket!=nullptr && tcpSocket->isOpen()){
tcpSocket->write(bytes);
}
else
qDebug()<<"disconnection";
}
.h
#ifndef SOCKET_H
#define SOCKET_H
#include <QObject>
#include <qtcpserver.h>
#include <qtcpsocket.h>
class socket : public QObject
{
Q_OBJECT
public:
explicit socket(QObject *parent = nullptr);
QByteArray m_bytes;
QTcpSocket *tcpSocket;
void ConnectServer(const QString &hostName,int port);
void WriteData(QByteArray bytes);
uint8_t getCheck(QByteArray bytes);
private:
int receiveLength;
public slots:
void readData();
};
#endif // SOCKET_H
注意
实例化需要在可访问ui线程中
m_socket = new socket(this);